Friday 22 July 2016

Create table in a database

I assumed the database ‘sample’ is already created, else create database sample using the statement ‘CREATE DATABASE sample’.


Syntax
CREATE TABLE table_name(
  column1 data_type,
  column2 data_type,
         ...
         ...
  columnn data_type,
  PRIMARY KEY(columns)
);

Step 1: Connect to MySQL server using statement ‘mysql -u user_name –p’.
$ mysql -u krishna -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.7.13 Homebrew

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 


Step 2: Suppose, I want to use the database ‘sample’. Command ‘USE sample’ 
is used to work with database sample.
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| sample             |
+--------------------+
2 rows in set (0.00 sec)

mysql> 
mysql> USE sample;
Database changed

STEP 3: use the statement ‘CREATE TABLE’ to create a table.


CREATE TABLE employee (id INT, name VARCHAR(20));
mysql> CREATE TABLE employee (id INT, name VARCHAR(20));
Query OK, 0 rows affected (0.01 sec)

You can use ‘DESCRIBE TABLE_NAME’ statement to get information about a table.


mysql> describe employee;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)


Previous                                                 Next                                                 Home

No comments:

Post a Comment