You are on page 1of 43

Manage Database in MySQL

In this lesson, you will learn how to manage databases in MySQL. You
will learn how to create new databases, remove existing databases, and
display all databases in the MySQL database server.
Creating Database
Before doing anything else with the data, you need to create a
database. A database is a container of data. It stores contacts, vendors,
customers or any kind of data that you can think of. In MySQL, a
database is a collection of objects that are used to store and
manipulate data such as tables, database views, triggers,
stored procedures, etc.
How to Create DB
• To create a database in MySQL, you use the CREATE DATABASE
statement as follows:

CREATE DATABASE [IF NOT EXISTS] database_name;


Displaying Databases
The SHOW DATABASES statement displays all databases in the MySQL
database server. You can use the SHOW DATABASES statement to check
the database that you’ve created or to see all the databases on the
database server before you create a new database, for example:

SHOW DATABASES;
Selecting a database to work with
Before working with a particular database, you must tell MySQL which
database you want to work with by using the USE statement.

USE database_name;
Removing Databases
Removing database means you delete the database physically. All the
data and associated objects inside the database are permanently
deleted and this cannot be undone. Therefore, it is very important to
execute this query with extra cautions.
To delete a database, you use the DROP DATABASE statement as
follows:

DROP DATABASE [IF EXISTS] database_name;


Understanding MySQL Table
Types, or Storage Engines
in this tutorial, you will learn various MySQL table types or storage engines. It is
essential to understand the features of each table type in MySQL so that you can
use them effectively to maximize the performance of your databases.
MySQL provides various storage engines
for its tables as below:
• MyISAM
• InnoDB
• MERGE
• MEMORY (HEAP)
• ARCHIVE
• CSV
• FEDERATED
Each storage engine has its own advantages and disadvantages. It is crucial to
understand each storage engine features and choose the most appropriate one for your
tables to maximize the performance of the database. In the following sections, we will
discuss each storage engine and its features so that you can decide which one to use.
MySQL Data Types
• in this tutorial, you will learn about MySQL data types and how to use
them effectively in designing database in MySQL.
• A database table contains multiple columns with specific data types
such as numeric or string. MySQL provides more data types other than
just numeric or string. Each data type in MySQL can be determined by
the following characteristics:
• The kind of values it represents.
• The space that takes up and whether the values is a fixed-length or variable
length.
• The values of the data type can be indexed or not.
• How MySQL compares the values of a specific data type.
Numeric Data Types
• The following table shows you the summary of numeric types in
MySQL:
TINYINT( ) -128 to 127 normal
0 to 255 UNSIGNED.
SMALLINT( ) -32768 to 32767 normal
0 to 65535 UNSIGNED.
-8388608 to 8388607 normal
MEDIUMINT( ) 0 to 16777215 UNSIGNED.

INT( ) -2147483648 to 2147483647 normal


0 to 4294967295 UNSIGNED.

BIGINT( ) -9223372036854775808 to 9223372036854775807 normal


0 to 18446744073709551615 UNSIGNED.
FLOAT A small number with a floating decimal point.
DOUBLE( , ) A large number with a floating decimal point.
DECIMAL( , ) A DOUBLE stored as a string, allowing for a fixed decimal point.
String Data Types
• The following table shows you the string data types in MySQL:
CHAR( ) A fixed section from 0 to 255 characters long.
VARCHAR( ) A variable section from 0 to 255 characters long.
TINYTEXT A string with a maximum length of 255 characters.
TEXT A string with a maximum length of 65535 characters.
BLOB A string with a maximum length of 65535 characters.
MEDIUMTEXT A string with a maximum length of 16777215 characters.
MEDIUMBLOB A string with a maximum length of 16777215 characters.
LONGTEXT A string with a maximum length of 4294967295 characters.
LONGBLOB A string with a maximum length of 4294967295 characters.
String Data Types (Conti…)
Short for ENUMERATION which means that each
column may have one of a specified possible values.
ENUM ( ) Ex:
CREATE TABLE length ( length ENUM('small',
'medium', 'large') );
insert into length values('small');
Similar to ENUM except each column may have more
than one of the specified possible values.
Ex:
SET CREATE TABLE length ( length SET('small', 'medium',
'large') );
insert into length values('small,medium');
Date and Time Data Types
• The following table illustrates the MySQL date and time data types:

DATE YYYY-MM-DD.
DATETIME YYYY-MM-DD HH:MM:SS.
TIMESTAMP YYYY-MM-DD HH:MM:SS.
TIME HH:MM:SS.
YEAR A year value in CCYY or YY format
Date and Time Data Types (Conti…)
• -Two-digit Year Support
MySQL pre-5.6.6
00-69=2000-2060
70-99=1970-1999
MySQL 5.6.6 and later
Deprecated
• -Standard SQL Date and Time format
2015-07-14 18:24:42 DATETIME YYYY-MM-DD HH:MM:SS.
• -Time Zone
SHOW VARIABLES LIKE ‘%time_zone%’;
SELECT Now();
SET time_zone=’US/Eastern’;
BOOLEAN DATA TYPE
• 0=False
• 1=True
CREATE TABLE

CREATE TABLE [IF NOT EXISTS] table_name(


column_name data_type[size] [NOT NULL|NULL]
[DEFAULT ‘SETEC’] [AUTO_INCREMENT][, …]
) engine=table_type;
Example of MySQL CREATE TABLE
statement
CREATE TABLE IF NOT EXISTS tasks (
  task_id int(11) NOT NULL,
  subject varchar(45) DEFAULT NULL,
  start_date DATE DEFAULT NULL,
  end_date DATE DEFAULT NULL,
  description varchar(200) DEFAULT NULL,
  PRIMARY KEY (task_id)
) ENGINE=InnoDB
ALTER TABLE

ALTER TABLE table_name


action1[,action2,…]
Add New Column
ALTER TABLE tasks
ADD COLUMN complete DECIMAL(2,1) NULL
AFTER description;
CHANGE Column
ALTER TABLE tasks
CHANGE COLUMN task_id task_id INT(11) NOT NULL
AUTO_INCREMENT;
Delete Column
ALTER TABLE tasks
DROP COLUMN description;
Rename Table Name
ALTER TABLE old_table_name
RENAME TO new_table_name;

Or

RENAME TABLE old_table_name TO new_table_name;


Index
• Create
CREATE INDEX office ON employees(officeCode);
• Show
SHOW INDEXES FROM tablesname;
• Drop
DROP INDEX office ON employees;
Unique Constraint
• Syntax:
ALTER TABLE table_name
ADD UNIQUE  name_unique (unique_key_colunmn ASC) ;
NOT NULL Constraint
ALTER TABLE table_name
CHANGE old_col new_col datatype NOT NULL;
Primary Key Constraint
• A primary key is a column or a set of columns that uniquely identifies
each row in the table.
• You must follow the rules below when you define a primary key for a
table:
• A primary key must contain unique values. If the primary key consists of
multiple columns, the combination of values in these columns must be
unique.
• A primary key column cannot contain NULL values. It means that you have to
declare the primary key column with the NOT NULL  attribute. If you don’t,
MySQL will force the primary key column as NOT NULL  implicitly.
• A table has only one primary key.
Defining MySQL PRIMARY KEY
Constraints
• using CREATE TABLE statement
• using ALTER TABLE statement
Defining MySQL PRIMARY KEY
constraints using CREATE TABLE
statement
• The following example creates users table whose primary key is
user_id column:

CREATE TABLE users(


   user_id INT AUTO_INCREMENT PRIMARY KEY,
   username VARCHAR(40),
   password VARCHAR(255),
   email VARCHAR(255)
);
Defining MySQL PRIMARY KEY
constraints using CREATE TABLE
statement (Conti…)
• You can also specify the PRIMARY KEY at the end of the CREATE TABLE
 statement as follows:

CREATE TABLE roles(


   role_id INT AUTO_INCREMENT,
   role_name VARCHAR(50),
   PRIMARY KEY(role_id)
);
Defining MySQL PRIMARY KEY
constraints using CREATE TABLE
statement (Conti…)
• In case the primary key consists of multiple columns, you must specify
them at the end of the CREATE TABLE  statement. You put a coma-
separated list of primary key columns inside parentheses followed the
PRIMARY KEY  keywords.

CREATE TABLE userroles(


   user_id INT NOT NULL,
   role_id INT NOT NULL,
   PRIMARY KEY(user_id,role_id)
);
Defining MySQL PRIMARY KEY
constraints using ALTER TABLE
statement
• Syntax:
ALTER TABLE table_name
ADD PRIMARY KEY(primary_key_column);
• Example
CREATE TABLE t1(
   id int,
   title varchar(255) NOT NULL
);

ALTER TABLE t1
ADD PRIMARY KEY(id);
Foreign Key Constraint
• A foreign key is a field in a table
that matches another field of
another table. A foreign key
places constraints on data in the
related tables, which enables
MySQL to maintain referential
integrity.
Defining MySQL FOREIGN KEY
Constraints
• using CREATE TABLE statement
• using ALTER TABLE statement

• Syntax:

FOREIGN KEY foreign_key_name (columns)


REFERENCES parent_table(columns)
ON DELETE CASCADE | ON DELETE SET NULL | ON DELETE RESTRICT
ON UPDATE CASCADE | ON UPDATE SET NULL | ON UPDATE RESTRICT
 
Defining MySQL FOREIGN KEY
constraints using CREATE TABLE
statement
CREATE DATABASE IF NOT EXISTS dbdemo; prd_id int not null auto_increment
primary key,
USE dbdemo; prd_name varchar(355) not null,
prd_price decimal,
CREATE TABLE categories( cat_id int not null,
cat_id int not null auto_increment FOREIGN KEY fk_cat(cat_id)
primary key, REFERENCES categories(cat_id)
cat_name varchar(255) not null, ON UPDATE CASCADE
cat_description text ON DELETE RESTRICT
) ENGINE=InnoDB; )ENGINE=InnoDB;
Defining MySQL FOREIGN KEY
constraints using ALTER TABLE
statement
CREATE TABLE vendors( AFTER cat_id;
vdr_id int not null auto_increment  
primary key, ALTER TABLE products
    vdr_name varchar(255) ADD FOREIGN KEY fk_vendor(vdr_id)
)ENGINE=InnoDB; REFERENCES vendors(vdr_id)
  ON DELETE NO ACTION
ALTER TABLE products ON UPDATE CASCADE;
ADD COLUMN vdr_id int not null
Disable and Enable Foreign key

SET foreign_key_checks = 0; -- Disable foreign key


 
SET foreign_key_checks = 1; -- Enable foreign key
Dropping MySQL foreign key
• To obtain the generated constraint name of a table, you use the
SHOW CREATE TABLE statement as follows:

SHOW CREATE TABLE table_name;

• Syntax:

ALTER TABLE table_name


DROP FOREIGN KEY constraint_name;
DROP TABLE
• Syntax:
DROP [TEMPORARY] TABLE [IF EXISTS] table_name [, table_name] ...
[RESTRICT | CASCADE]

• To Check Message after drop table


SHOW WARNINGS;

• You can use LIKE Operator to Drop table


DROP TABLE LIKE '%pattern%'
-- set table schema and pattern matching for tables
SET @schema = 'classicmodels';
SET @pattern = 'test%';
 
-- build dynamic sql (DROP TABLE tbl1, tbl2...;)
SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(distinct CONCAT(@schema,'.',table_name)),';')
INTO @droplike
FROM information_schema.tables
WHERE @schema = database()
AND table_name LIKE @pattern and table_schema=@schema;
 
-- display the dynamic sql statement
SELECT @droplike;
 
-- execute dynamic sql
PREPARE stmt FROM @droplike;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Transaction
To understand what a transaction in MySQL is, let’s take a look at an
example of adding a new sales order in our sample database. The steps of
adding a sales order are as described as follows:
• Query the latest sales order number from the orders table, and use the next sales
order number as the new sales order number.
• Insert a new sales order into the orders table for a given customer.
• Insert new sales order items into the orderdetails table.
• Get data from both table orders and orderdetails tables to confirm the changes
Now imagine what would happen to your data if one or more steps above
fail because of database failure such as table lock security? If the step of
adding order items into orderdetails table failed, you would have an empty
sales order in your system without knowing it.
How to Create Transaction
• To start a transaction
START TRANSACTION;
• To undo MySQL statements
ROLLBACK;
• To write the changes into the database within a transaction
COMMIT;
• MySQL automatically commits the changes to the database by default. To force
MySQL not to commit changes automatically, you use the following statement:
SET autocommit = 0;
• Note: DDL Statement like Create/Alter/Drop table … can not use rollback.
-- start a new transaction date_add(now(), INTERVAL 2 DAY),
start transaction; 'In Process',
145);
-- get latest order number -- insert 2 order line items
select @orderNumber :=max(orderNumber) insert into orderdetails(orderNumber,
from orders; productCode,
-- set new order number quantityOrdered,
set @orderNumber = @orderNumber + 1; priceEach,
orderLineNumber)
-- insert a new order for customer 145 values(@orderNumber,'S18_1749', 30, '136', 1),
insert into orders(orderNumber, (@orderNumber,'S18_2248', 50, '55.09', 2);
orderDate, -- commit changes
requiredDate, commit;
shippedDate,
status, -- get the new inserted order
customerNumber) select * from orders a
values(@orderNumber, inner join orderdetails b on a.ordernumber =
b.ordernumber
now(),
where a.ordernumber = @ordernumber;
date_add(now(), INTERVAL 5 DAY),
MySQL Table Lock
• MySQL allows a client session to acquire a table lock explicitly for preventing other
sessions from accessing the table during a specific period. A client session can acquire
or release table locks only for itself. It cannot acquire or release table locks for other
sessions.
• Lock Syntax:
LOCK TABLES table_name [READ | WRITE]
• Unlock Syntax:
UNLOCK TABLES;
• To find out the current connection id
SELECT CONNECTION_ID();
• To see the detailed information from the SHOW PROCESSLIST statement
SHOW PROCESSLIST;

You might also like