Mysql Comments

How to Copy backup a MySQL Database

Posted on Updated on

The mysqldump Command

The mysqldump command creates a text version of the database. Specifically, it creates a list of SQL statements which can be used to restore/recreate the original database.

# mysqldump -uusername -ppasswd dbname > backupfile.sql


# mysqldump -B openfire > /home/db.sql


# mysqldump –all-databases -r dbdump.sql -uroot-p

[username] Your database username
[passwd] The password for your database
[dbname] The name of your database
[backupfile.sql] The filename for your database backup

You can dump a table, a database, or all databases.

To dump all MySQL databases on the system, use the –all-databases shortcut:

# mysqldump -u root -p –all-databases > backupfile.sql

Restoring a MySQL Database

Use this method to rebuild a database from scratch

# mysql -u username -p passwd database_to_restore < /path/to/file.sql

Use this method to import into an existing database (i.e. to restore a database that already exists)

# mysqlimport -u sadmin -p pass21 db_name DBback.sql


# mysqlimport options database textfile


mysql>use dbname; <select the existing DB >
mysql>source /home/db.sql; <restore backup to the db>

Short List of MySQL Commands

Posted on Updated on

Conventions used here:

* MySQL key words are shown in CAPS
* User-specified names are in small letters
* Optional items are enclosed in square brackets [ ]
* Items in parentheses must appear in the command, along with the parentheses
* Items that can be repeated as often as desired are indicated by an ellipsis …

Quoting in MySQL statments

* Don’t quote database, table, or column names
* Don’t quote column types or modifiers
* Don’t quote numerical values
* Quote (single or double) non-numeric values
* Quote file names and passwords
* User names are NOT quoted in GRANT or REVOKE statements, but they are quoted in other statements.

General Commands

USE database_name
Change to this database. You need to change to some database when you first connect to MySQL.

Lists all MySQL databases on the system.

SHOW TABLES [FROM database_name]
Lists all tables from the current database or from the database given in the command.

DESCRIBE table_name
These commands all give a list of all columns (fields) from the given table, along with column type and other info.

SHOW INDEX FROM table_name
Lists all indexes from this tables.

Allows the user to set his/her own password.

Table Commands

CREATE TABLE table_name (create_clause1, create_clause2, …)
Creates a table with columns as indicated in the create clauses.

column name followed by column type, followed optionally by modifiers. For example, “gene_id INT AUTO_INCREMENT PRIMARY KEY” (without the quotes) creates a column of type integer with the modifiers described below.

create_clause modifiers

* AUTO_INCREMENT : each data record is assigned the next sequential number when it is given a NULL value.
* PRIMARY KEY : Items in this column have unique names, and the table is indexed automatically based on this column. One column must be the PRIMARY KEY, and only one column may be the PRIMARY KEY. This column should also be NOT NULL.
* NOT NULL : No NULL values are allowed in this column: a NULL generates an error message as the data is inserted into the table.
* DEFAULT value : If a NULL value is used in the data for this column, the default value is entered instead.

DROP TABLE table_name
Removes the table from the database. Permanently! So be careful with this command!

ALTER TABLE table_name ADD (create_clause1, create_clause2, …)
Adds the listed columns to the table.

ALTER TABLE table_name DROP column_name
Drops the listed columns from the table.

ALTER TABLE table_name MODIFY create_clause
Changes the type or modifiers to a column. Using MODIFY means that the column keeps the same name even though its type is altered. MySQL attempts to convert the data to match the new type: this can cause problems.

ALTER TABLE table_name CHANGE column_name create_clause
Changes the name and type or modifiers of a column. Using CHANGE (instead of MODIFY) implies that the column is getting a new name.

ALTER TABLE table_name ADD INDEX [index_name] (column_name1, column_name2, …)
CREATE INDEX index_name ON table_name (column_name1, column_name2, …)
Adds an index to this table, based on the listed columns. Note that the order of the columns is important, because additional indexes are created from all subsets of the listed columns reading from left to write. The index name is optional if you use ALTER TABLE, but it is necesary if you use CREATE INDEX. Rarely is the name of an index useful (in my experience).

Data Commands

INSERT [INTO] table_name VALUES (value1, value2, …)
Insert a complete row of data, giving a value (or NULL) for every column in the proper order.

INSERT [INTO] table_name (column_name1, column_name2, …) VALUES (value1, value2, …)
INSERT [INTO] table_name SET column_name1=value1, column_name2=value2, …
Insert data into the listed columns only. Alternate forms, with the SET form showing column assignments more explicitly.

INSERT [INTO] table_name (column_name1, column_name2, …) SELECT list_of_fields_from_another_table FROM other_table_name WHERE where_clause
Inserts the data resulting from a SELECT statement into the listed columns. Be sure the number of items taken from the old table match the number of columns they are put into!

DELETE FROM table_name WHERE where_clause
Delete rows that meet the conditions of the where_clause. If the WHERE statement is omitted, the table is emptied, although its structure remains intact.

UPDATE table_name SET column_name1=value1, column_name2=value2, … [WHERE where_clause]
Alters the data within a column based on the conditions in the where_clause.

LOAD DATA LOCAL INFILE ‘path to external file’ INTO TABLE table_name
Loads data from the listed file into the table. The default assumption is that fields in the file are separated by tabs, and each data record is separated from the others by a newline. It also assumes that nothing is quoted: quote marks are considered to be part of the data. Also, it assumes that the number of data fields matches the number of table columns. Columns that are AUTO_INCREMENT should have NULL as their value in the file.

LOAD DATA LOCAL INFILE ‘path to external file’ [FIELDS TERMINATED BY ‘termination_character’] [FIELDS ENCLOSED BY ‘quoting character’] [LINES TERMINATED BY ‘line termination character’] FROM table_name
Loads data from the listed file into the table, using the field termination character listed (default is tab \t), and/or the listed quoting character (default is nothing), and/or the listed line termination chacracter (default is a newline \n).

SELECT column_name1, column_name2, … INTO OUTFILE ‘path to external file’ [FIELDS TERMINATED BY ‘termination_character’] [FIELDS ENCLOSED BY ‘quoting character’] [LINES TERMINATED BY ‘line termination character’] FROM table_name [WHERE where_clause]
Allows you to move data from a table into an external file. The field and line termination clauses are the same as for LOAD above. Several tricky features:

1. Note the positions of the table_name and where_clause, after the external file is given.
2. You must use a complete path, not just a file name. Otherwise MySQL attempts to write to the directory where the database is stored, where you don’t have permission to write.
3. The user who is writing the file is ‘mysql’, not you! This means that user ‘mysql’ needs permission to write to the directory you specify. The best way to do that is to creat a new directory under your home directory, then change the directory’s permission to 777, then write to it. For example: mkdir mysql_output, chmod 777 mysql_output.

Privilege Commands

Most of the commands below require MySQL root access

GRANT USAGE ON *.* TO user_name@localhost [IDENTIFIED BY ‘password’]
Creates a new user on MySQL, with no rights to do anything. The IDENTIFED BY clause creates or changes the MySQL password, which is not necessarily the same as the user’s system password. The @localhost after the user name allows usage on the local system, which is usually what we do; leaving this off allows the user to access the database from another system. User name NOT in quotes.

GRANT SELECT ON *.* TO user_name@localhost
In general, unless data is supposed to be kept private, all users should be able to view it. A debatable point, and most databases will only grant SELECT privileges on particular databases. There is no way to grant privileges on all databses EXCEPT specifically enumerated ones.

GRANT ALL ON database_name.* TO user_name@localhost
Grants permissions on all tables for a specific database (database_name.*) to a user. Permissions are for: ALTER, CREATE, DELETE, DROP, INDEX, INSERT, SELECT, UPDATE.

Needed to get updated privileges to work immediately. You need RELOAD privileges to get this to work.

Allows the user to set his/her own password.

REVOKE ALL ON [database_name.]* FROM user_name@localhost
Revokes all permissions for the user, but leaves the user in the MySQL database. This can be done for all databases using “ON *”, or for all tables within a specific databse, using “ON database_name.*”.

DELETE FROM mysql.user WHERE user=’user_name@localhost’
Removes the user from the database, which revokes all privileges. Note that the user name is in quotes here.

UPDATE mysql.user SET password=PASSWORD(‘my_password’) WHERE user=’user_name’
Sets the user’s password. The PASSWORD function encrypts it; otherwise it will be in plain text.

SELECT user, host, password, select_priv, insert_priv, shutdown_priv, grant_priv FROM mysql.user
A good view of all users and their approximate privileges. If there is a password, it will by an encrytped string; if not, this field is blank. Select is a very general privlege; insert allows table manipulation within a database; shutdown allows major system changes, and should only be usable by root; the ability to grant permissions is separate from the others.

SELECT user, host, db, select_priv, insert_priv, grant_priv FROM mysql.db
View permissions for individual databases.

MY SQL basic commands

Posted on Updated on

My  SQL Basic commands

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,User,Password) VALUES(‘%’,’username’,PASSWORD(‘password’));
mysql> flush privileges;
Change a users password from unix shell.

# [mysql dir]/bin/mysqladmin -u username -h -p password ‘new-password’
Change a users password from MySQL prompt. Login as root. Set the password. Update privs.

# mysql -u root -p
mysql> SET PASSWORD FOR ‘user’@’hostname’ = PASSWORD(‘passwordhere’);
mysql> flush privileges;
Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.

# /etc/init.d/mysql stop
# mysqld_safe –skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD(“newrootpassword”) where User=’root’;
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
Set a root password if there is on root password.

# mysqladmin -u root password newpassword
Update a root password.

# mysqladmin -u root -p oldpassword newpassword
Allow the user “bob” to connect to the server from localhost using the password “passwd”. Login as root. Switch to the MySQL db. Give privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to bob@localhost identified by ‘passwd’;
mysql> flush privileges;
Give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES (‘%’,’databasename’,’username’,’Y’,’Y’,’Y’,’Y’,’Y’,’N’);
mysql> flush privileges;


mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;
To update info already in a table.

mysql> UPDATE [table name] SET Select_priv = ‘Y’,Insert_priv = ‘Y’,Update_priv = ‘Y’ where [field name] = ‘user’;
Delete a row(s) from a table.

mysql> DELETE from [table name] where [field name] = ‘whatever’;
Update database permissions/privilages.

mysql> flush privileges;
Delete a column.

mysql> alter table [table name] drop column [column name];
Add a new column to db.

mysql> alter table [table name] add column [new column name] varchar (20);
Change column name.

mysql> alter table [table name] change [old column name] [new column name] varchar (50);
Make a unique column so you get no dupes.

mysql> alter table [table name] add unique ([column name]);
Make a column bigger.

mysql> alter table [table name] modify [column name] VARCHAR(3);
Delete unique from table.

mysql> alter table [table name] drop index [colmn name];
Load a CSV file into a table.

mysql> LOAD DATA INFILE ‘/tmp/filename.csv’ replace INTO TABLE [table name] FIELDS TERMINATED BY ‘,’ LINES TERMINATED BY ‘\n’ (field1,field2,field3);
Dump all databases for backup. Backup file is sql commands to recreate all db’s.

# [mysql dir]/bin/mysqldump -u root -ppassword –opt >/tmp/alldatabases.sql
Dump one database for backup.

# [mysql dir]/bin/mysqldump -u username -ppassword –databases databasename >/tmp/databasename.sql
Dump a table from a database.

# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql
Restore database (or database table) from backup.

# [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql
Create Table Example 1.

mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));
Create Table Example 2.

mysql> create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastnamevarchar(50) default ‘bato’);

Manage MySQL Databases

Posted on Updated on

This scripts will create db, db user and a password

grant select, insert, update, delete, create, drop, index, alter, create temporary tables, lock tables ,CREATE VIEW,CREATE ROUTINE, EXECUTE, ALTER ROUTINE on slocal.* to dbslocal@localhost identified by ‘H2Zy#4W’;

grant all on <db>.* to <user>@”%” identified by ‘passwd’;

1. To login (from unix shell) use -h only if needed.

# [mysql dir]/bin/mysql -h hostname -u root -p

2. Create a database on the sql server.

mysql> create database [databasename];

3.List all databases on the sql server.

mysql> show databases;

4. Switch to a database.

mysql> use [db name];

5. To see all the tables in the db.

mysql> show tables;

6.To see database’s field formats.

mysql> describe [table name];

7.To delete a db.

mysql> drop database [database name];

8.To delete a table.

mysql> drop table [table name];

9.Show all data in a table.

mysql> SELECT * FROM [table name];

10.Returns the columns and column information pertaining to the designated table.

mysql> show columns from [table name];

11.Show certain selected rows with the value “whatever”.

mysql> SELECT * FROM [table name] WHERE [field name] = “whatever”;

12.Show all records containing the name “Bob” AND the phone number ‘3444444’.

mysql> SELECT * FROM [table name] WHERE name = “Bob” AND phone_number = ‘3444444’;

13.Show all records not containing the name “Bob” AND the phone number ‘3444444’ order by the phone_number field.

mysql> SELECT * FROM [table name] WHERE name != “Bob” AND phone_number = ‘3444444’ order by phone_number;

14.Show all records starting with the letters ‘bob’ AND the phone number ‘3444444’.

mysql> SELECT * FROM [table name] WHERE name like “Bob%” AND phone_number = ‘3444444’;

15.Show all records starting with the letters ‘bob’ AND the phone number ‘3444444’ limit to records 1 through 5.

mysql> SELECT * FROM [table name] WHERE name like “Bob%” AND phone_number = ‘3444444’ limit 1,5;

16. Use a regular expression to find records. Use “REGEXP BINARY” to force case-sensitivity. This finds any record beginning with a.

mysql> SELECT * FROM [table name] WHERE rec RLIKE “^a”;

17. Show unique records.

mysql> SELECT DISTINCT [column name] FROM [table name];

18. Show selected records sorted in an ascending (asc) or descending (desc).

mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;

19. Return number of rows.

mysql> SELECT COUNT(*) FROM [table name];

20. Sum column.

mysql> SELECT SUM(*) FROM [table name];

21. Join tables on common columns.

mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on

22.lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;

Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.