Wednesday, November 28, 2012

MySQL Cheat Sheet

In this article, you will find common usage MySQL commands in one page to help you to practice with MySQL fast and effectively.

Working with Database

Create a database with a specified name if it does not exist in database server
1CREATE DATABASE [IF NOT EXISTS] database_name

Use database or change current database to another database you are working with
1USE database_name
Drop a database with specified name permanently. All physical file associated with the database is no longer exists.
1DROP DATABASE [IF EXISTS] database_name
Show all available databases in database server
1SHOW DATABASES

Working with Table

Lists all tables in a database.
1SHOW TABLES
Create table statement defines the structure of table in a database.
1CREATE [TEMPORARY] TABLE [IF NOT EXISTS] table_name
2(create_clause ,...) [table_options]
3[[IGNORE|REPLACE] select
]
Altering table structure
Actions can be one of the following actions:
1ADD [COLUMN]
Add a new column into a table
1DROP [COLUMN]
Drop an existing column in a table
1ADD INDEX [name](column_name, ...)
Add index with a specific name to a table on a column
1DROP INDEX index_name Drop an index from a table
ADD PRIMARY KEY (column_name,...)
Add primary key into a tables
1DROP PRIMARY KEY
Drop primary key from a table
Deleting table permanently
1DROP TABLE [IF EXISTS] table_name [, name2, ...]
2[RESTRICT | CASCADE]
Give information about the table or column.
1DESCRIBE table [column_name]
2DESC table [column_name

Working with Index

Creating an index with the specified name on a table
1CREATE [UNIQUE|FULLTEXT] INDEX index_name
2ON table (column_name,...)
Removing a specified index from table
1DROP INDEX index_name

Retrieving Data

Retrieving complete data in a database table
1SELECT * FROM table_name
Retrieving specified data which is shown in the column list from a database table
1SELECT column_name, column_name2….
2FROM table_name
Retrieving unique records
1SELECT DISTINCT (column_name)
2FROM table_name
Retrieving data from multiples table using join
1SELECT *
2FROM table_name1
3INNER JOIN table_name2 ON conditions
1SELECT *
2FROM table_name1
3LEFT JOIN table_name2 ON conditions
1SELECT *
2FROM table_name1
Counting number of rows in a database table
1SELECT COUNT (*)
2FROM table_name
Sorting ascending or descending retrieved data based on one or more column
1SELECT column_name, column_name2….
2FROM table_name
3ORDER BY column_name ASC [DESC], column_name2 ASC [DESC],...
Group the retrieved rows data
1SELECT *
2FROM table_name
3GROUP BY column_name

Matching Data based on a pattern

Matching data using LIKE operator
1SELECT * FROM table_name
2WHERE column_name LIKE ‘%value%’

Matching data using regular expression

1SELECT * FROM table_name
2WHERE column_name RLIKE ‘regular_expression’

No comments:

Post a Comment