Access monitor: mysql -u [username] -p;
(will prompt for password)
Show all databases: show databases;
Access database: mysql -u [username] -p [database]
(will prompt for password)
Create new database: create database [database];
Select database: use [database];
Determine what database is in use: select database();
Show all tables: show tables;
Show table structure: describe [table];
List all indexes on a table: show index from [table];
Create new table with columns: CREATE TABLE [table] ([column] VARCHAR(120), [another-column] DATETIME);
Adding a column: ALTER TABLE [table] ADD COLUMN [column] VARCHAR(120);
Adding a column with an unique, auto-incrementing ID: ALTER TABLE [table] ADD COLUMN [column] int NOT NULL AUTO_INCREMENT PRIMARY KEY;
Inserting a record: INSERT INTO [table] ([column], [column]) VALUES ('[value]', [value]');
MySQL function for datetime input: NOW()
Selecting records: SELECT * FROM [table];
Explain records: EXPLAIN SELECT * FROM [table];
Selecting parts of records: SELECT [column], [another-column] FROM [table];
Counting records: SELECT COUNT([column]) FROM [table];
Counting and selecting grouped records: SELECT *, (SELECT COUNT([column]) FROM [table]) AS count FROM [table] GROUP BY [column];
Selecting specific records: SELECT * FROM [table] WHERE [column] = [value];
(Selectors: <
, >
, !=
; combine multiple selectors with AND
, OR
)
Select records containing [value]
: SELECT * FROM [table] WHERE [column] LIKE '%[value]%';
Select records starting with [value]
: SELECT * FROM [table] WHERE [column] LIKE '[value]%';
Select records starting with val
and ending with ue
: SELECT * FROM [table] WHERE [column] LIKE '[val_ue]';
Select a range: SELECT * FROM [table] WHERE [column] BETWEEN [value1] and [value2];
Select with custom order and only limit: SELECT * FROM [table] WHERE [column] ORDER BY [column] ASC LIMIT [value];
(Order: DESC
, ASC
)
Updating records: UPDATE [table] SET [column] = '[updated-value]' WHERE [column] = [value];
Deleting records: DELETE FROM [table] WHERE [column] = [value];
Delete all records from a table (without dropping the table itself): DELETE FROM [table];
(This also resets the incrementing counter for auto generated columns like an id column.)
Delete all records in a table: truncate table [table];
Removing table columns: ALTER TABLE [table] DROP COLUMN [column];
Deleting tables: DROP TABLE [table];
Deleting databases: DROP DATABASE [database];
Custom column output names: SELECT [column] AS [custom-column] FROM [table];
Export a database dump (more info here): mysqldump -u [username] -p [database] > db_backup.sql
Use --lock-tables=false
option for locked tables (more info here).
Import a database dump (more info here): mysql -u [username] -p -h localhost [database] < db_backup.sql
Logout: exit;
Aggregate functions
Select but without duplicates: SELECT distinct name, email, acception FROM owners WHERE acception = 1 AND date >= 2015-01-01 00:00:00
Calculate total number of records: SELECT SUM([column]) FROM [table];
Count total number of [column]
and group by [category-column]
: SELECT [category-column], SUM([column]) FROM [table] GROUP BY [category-column];
Get largest value in [column]
: SELECT MAX([column]) FROM [table];
Get smallest value: SELECT MIN([column]) FROM [table];
Get average value: SELECT AVG([column]) FROM [table];
Get rounded average value and group by [category-column]
: SELECT [category-column], ROUND(AVG([column]), 2) FROM [table] GROUP BY [category-column];
Multiple tables
Select from multiple tables: SELECT [table1].[column], [table1].[another-column], [table2].[column] FROM [table1], [table2];
Combine rows from different tables: SELECT * FROM [table1] INNER JOIN [table2] ON [table1].[column] = [table2].[column];
Combine rows from different tables but do not require the join condition: SELECT * FROM [table1] LEFT OUTER JOIN [table2] ON [table1].[column] = [table2].[column];
(The left table is the first table that appears in the statement.)
Rename column or table using an alias: SELECT [table1].[column] AS '[value]', [table2].[column] AS '[value]' FROM [table1], [table2];
Users functions
List all users: SELECT User,Host FROM mysql.user;
Create new user: CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
Grant ALL
access to user for *
tables: GRANT ALL ON database.* TO 'user'@'localhost';
https://gist.github.com/hofmannsven/9164408
ggg
Handy MySQL Commands | ||
Description | Command | |
To login (from unix shell) use -h only if needed. | [mysql dir]/bin/mysql -h hostname -u root -p | |
Create a database on the sql server. | create database [databasename]; | |
List all databases on the sql server. | show databases; | |
Switch to a database. | use [db name]; | |
To see all the tables in the db. | show tables; | |
To see database’s field formats. | describe [table name]; | |
To delete a db. | drop database [database name]; | |
To delete a table. | drop table [table name]; | |
Show all data in a table. | SELECT * FROM [table name]; | |
Returns the columns and column information pertaining to the designated table. | show columns from [table name]; | |
Show certain selected rows with the value “whatever”. | SELECT * FROM [table name] WHERE [field name] = “whatever”; | |
Show all records containing the name “Bob” AND the phone number ‘3444444’. | SELECT * FROM [table name] WHERE name = “Bob” AND phone_number = ‘3444444’; | |
Show all records not containing the name “Bob” AND the phone number ‘3444444’ order by the phone_number field. | SELECT * FROM [table name] WHERE name != “Bob” AND phone_number = ‘3444444’ order by phone_number; | |
Show all records starting with the letters ‘bob’ AND the phone number ‘3444444’. | SELECT * FROM [table name] WHERE name like “Bob%” AND phone_number = ‘3444444’; | |
Use a regular expression to find records. Use “REGEXP BINARY” to force case-sensitivity. This finds any record beginning with a. | SELECT * FROM [table name] WHERE rec RLIKE “^a$”; | |
Show unique records. | SELECT DISTINCT [column name] FROM [table name]; | |
Show selected records sorted in an ascending (asc) or descending (desc). | SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC; | |
Count rows. | SELECT COUNT(*) FROM [table name]; | |
Join tables on common columns. | select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id; |
|
Switch to the mysql db. Create a new user. | INSERT INTO [table name] (Host,User,Password) VALUES(‘%’,’user’,PASSWORD(‘password’)); | |
Change a users password.(from unix shell). | [mysql dir]/bin/mysqladmin -u root -h hostname.blah.org -p password ‘new-password’ | |
Change a users password.(from MySQL prompt). | SET PASSWORD FOR ‘user’@’hostname’ = PASSWORD(‘passwordhere’); | |
Switch to mysql db.Give user privilages for a db. | INSERT INTO [table name] (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES (‘%’,’db’,’user’,’Y’,’Y’,’Y’,’Y’,’Y’,’N’); | |
To update info already in a table. | UPDATE [table name] SET Select_priv = ‘Y’,Insert_priv = ‘Y’,Update_priv = ‘Y’ where [field name] = ‘user’; | |
Delete a row(s) from a table. | DELETE from [table name] where [field name] = ‘whatever’; | |
Update database permissions/privilages. | FLUSH PRIVILEGES; | |
Delete a column. | alter table [table name] drop column [column name]; | |
Add a new column to db. | alter table [table name] add column [new column name] varchar (20); | |
Change column name. | alter table [table name] change [old column name] [new column name] varchar (50); | |
Make a unique column so you get no dupes. | alter table [table name] add unique ([column name]); | |
Make a column bigger. | alter table [table name] modify [column name] VARCHAR(3); | |
Delete unique from table. | alter table [table name] drop index [colmn name]; | |
Load a CSV file into a table. | 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. | 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. | create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastname varchar(50) default ‘bato’);
http://g2pc1.bu.edu/~qzpeng/manual/MySQL%20Commands.htm |
Ask a Question:
You must be logged in to post a comment.