Friday, March 11, 2016

MySQL Queries and commands


In this post I hope to go through some MySQL commands that would help users get started and used to using it. Remember that semicolons are default used to show end of command/queries.

Creation/Deletion Commands

USE <database name>:
This is used to enter an existing database.

CREATE DATABASE <database name>:
This is used to create a database.

CREATE TABLE <table name> <name of variable, variable type>:
This is really similar to database creation, although it has many more entries for each attribute. Here are some commonly used ones:

  • CHAR(N), where N is length between 1-255. Default is 1
  • VARCHAR(N), where N is length between 1-255. Unlike CHAR, you must define a length.
  • INT, an integer entry. The number should be between -2147483648 and 2147483648. If you need a bigger number, you can use
  • BIGINT the integer max depends on signed or unsigned.
SHOW TABLES:
Shows all available tables in a database

SHOW DATABASES:
Shows all existing databases in MySQL

DESCRIBE <table name>:
This shows how you've defined the table, what variables and types.

DROP TABLE <table name>:
This totally deletes the table, if it exists of course.

DROP DATABASE <database name>:

This deletes an existing database

Query Commands

SELECT * FROM <table name> WHERE <some condition>:
Select *  means it finds some table and return everything. If you want to find something specific you would do SELECT <attribute name> FROM <table name>  and if you want to return pairs of things you can specifiy the attributes with commas.
Ex.  SELECT name, age FROM attendees WHERE age > 20;

FROM describes where you are searching/querying.
WHERE is specifying conditions, you can specify several conditions in separated AND or OR.

AND:
The and keyword is used to specify that the combined conditions must all be satisfied.
Ex.  SELECT name, age FROM attendees WHERE age > 20 AND age < 30;

OR:
The or keyword is used to specify that one of the combined conditions must be satisfied.
Ex.  SELECT name, age FROM attendees WHERE age > 20 OR age < 10;

These are just the few basic commands/queries that you can do, and I hope that this helps you get started with building a database! I also plan to publish a post that goes into more queries, since most database management concepts are about these queries.