AidanMontareDotNet

You are on the old part of aidanmontare.net, which I am no longer maintaining. Newer versions of some of this content can be found on the active part of my site, which you can reach from my homepage.

MySQL Cheatsheet

(last updated

Rarely does using WordPress require any interaction with the MySQL database that store’s all your site’s information. However, it is occasionally useful to know how to interact with the database directly. Since MySQL commands can be a little confusing for those who are not familiar with them, here is my reference page for using the MySQL command line interface.

Logging In

mysql -u [USERNAME] -p [DATABASE NAME]
Enter your database user’s password and you will be greeted with a MySQL prompt.

A Note About Case Sensitivity

MySQL commands are not case sensitive, but it is by convention that the commands are in uppercase and the database stuff is in lowercase. I will follow this convention here, but feel free to be lazy and not capitalize your commands if you wish! Note that the names of databases, tables, values, etc. may be case sensitive, depending on your system.

Dealing With Long Outputs

Sometimes you may have a very large table to output, such as the table containing all of your posts on a WordPress site. If your console is not absurdly large, chances are you won’t be able to view that all on one screen. However, pager less -n -i -S on the mysql prompt will allow results to be sent to the less program, so you can scroll through them (the -S option makes long lines not wrap, so use the arrow keys to scroll left and right to view more table columns). Read the MySQL manual page for more information on some neat output methods, such as sending table output to a file.

Finding What’s There

Show all databases on the server:
SHOW databases;
Show all tables in a database:
SHOW tables FROM [DATABASE];

Viewing the Contents of Tables

Show all contents of a table:
SELECT * FROM [TABLE]
Show all contents whose field [FIELD] is [VALUE]:
SELECT * FROM [TABLE] WHERE [FIELD] = [VALUE]
Put value in quotes if it is a string.

Deleting a Row of a Table

As a good measure, run a database backup before you go messing with the database for a live site.
First use SELECT to see if you have the correct search:
SELECT * FROM [TABLE] WHERE [FIELD] = [VALUE];
Play with [FIELD] and [VALUE] until only the row or rows you want to delete are returned.
When only the correct rows are returned, run the same exact command, but replace SELECT * with DELETE:
DELETE FROM [TABLE] WHERE [FIELD] = [VALUE];

References

from which I learned most of this stuff
http://dev.mysql.com/doc/refman/5.5/en/identifier-case-sensitivity.html
http://www.ehow.com/how_2094999_delete-from-mysql-database.html
http://oak.cs.ucla.edu/cs144/projects/mysql/
http://dev.mysql.com/doc/refman/5.5/en/delete.html