Skip to content

Instantly share code, notes, and snippets.

@RicardoWEBSiTE
Created September 3, 2013 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RicardoWEBSiTE/6427429 to your computer and use it in GitHub Desktop.
Save RicardoWEBSiTE/6427429 to your computer and use it in GitHub Desktop.

MySQL

A database system.

Logging into MySQL

$ mysql

or

$ mysql -u username -p
Enter password:

It's a good practice to setup different users with access to specific databases. N.B. Don't use the root account for user databases.

Let's assign a unique password to the root user:

$ mysql -u root -p
mysql> SET PASSWORD FOR root@localhost = PASSWORD('root');

See SET PASSWORD for further details.

Working with MySQL from the Terminal

# Showing the databases
mysql> SHOW DATABASES;

# Creating a database
mysql> CREATE DATABASE blog;

# Using a specific database
mysql> USE blog;

# Showing the tables in the database
mysql> SHOW TABLES;

# Creating a table
mysql> CREATE TABLE users(
    ->   id INT AUTO_INCREMENT,
    ->   first_name varchar(50) NOT NULL,
    ->   last_name varchar(50) NOT NULL,
    ->   email_address varchar(100) NOT NULL,
    ->   PRIMARY KEY (id)
    -> );

# Viewing the structure of a table, i.e. it's schema
mysql> DESCRIBE users;

# Selecting all rows from a table
mysql> SELECT * FROM users;

Inserting, Selecting, and Deleting

mysql> INSERT INTO users VALUES(null, 'John', 'Doe', 'john@doe.com');

or

mysql> INSERT INTO users (first_name, last_name, email_address) VALUES('John', 'Doe', 'john@doe.com');
mysql> SELECT email_address FROM users;
mysql> SELECT first_name, last_name FROM users;

Ordering your selections:

mysql> SELECT * FROM users ORDER BY last_name ASC;
mysql> SELECT * FROM users ORDER BY last_name DESC;

Limiting the number of rows returned:

mysql> SELECT * FROM users LIMIT 2;
mysql> DELETE FROM users WHERE [condition];

mysql> DELETE FROM users WHERE id = 123;
mysql> DELETE FROM users WHERE last_name = 'Crooks';

Updating Rows and Tables

To update a row in a table we use the UPDATE query.

mysql> UPDATE users SET last_name = 'Alexander' WHERE first_name = 'Jane';

To change a column name and type in a table use the ALTER query.

mysql> ALTER TABLE users CHANGE last_name surname varchar(80);

Joining Tables

GUI Apps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment