ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

SQL Create Table

sqltuts
Create is used to define new tables.

Syntax :

  1. CREATE TABLE <table_name>
  2. (
  3.  <Field1>   <Type> <(width)>Constraint <constraint name> Primary Key,
  4.   <Field2>  <Type> <(width)>,
  5. ..................................
  6. ) ;

 

The above syntax can be used for creating tables with the primary key. Here field1 is the column name, Type is the data type of the column like int, char, varchar etc. and width specifies the maximum length of the column of the table.

 

The syntax for creating a table with composite primary key.

  1. Create table <Table Name>
  2. (
  3.   <Field1>  <Type> <(width)> ,
  4.   <Field2>  <Type> <(width)>,
  5.     ..................................<field-n> <type-n> <width-n>,
  6. Constraint <constraint-name> Primary Key (Field1, Field2)
  7. ) ;

 

Example:

 

  1. CREATE TABLE employee
  2. (
  3. Employee_id  int,
  4. Name Varchar(25),
  5. Address Varchar (50)
  6. );

 

The Employee_id column is of int type and will hold integers. Rest all are of type varchar and will hold characters. For Name maximum number of characters can be 25 whereas for Address maximum number of characters can be 50.

  1. tutorials_Person(
  2.    tutorial_id,
  3.    tutorial_FName VARCHAR(50) NOT NULL,
  4.    tutorial_Lname VARCHAR(30) NOT NULL,
  5.    submission_fee FEE,
  6.    PRIMARY KEY ( tutorial_id )
  7. );

 

 

A creation of a  table using PHP script:

 

  1. <html>
  2. <head>
  3. <title>Creating MySQL Tables for a given Database</title>
  4. </head>
  5. <body>
  6. <?php
  7. $dbhost = 'localhost';
  8. $dbusername = 'root';
  9. $dbpassword = 'rootpassword';
  10. $conn = mysql_connect($dbhost, $dbuser, $dbpass);
  11. if(! $con )
  12. {
  13.   die('Could not connect: ' . mysql_error());
  14. }
  15. echo 'Connected successfully<br />';
  16. $sql = "CREATE TABLE tutorials_Person( ". tutorial_id,
  17.    “tutorial_FName VARCHAR(50) NOT NULL,.
  18.    “tutorial_Lname VARCHAR(30) NOT NULL,.
  19.   “ submission_fee FEE,.
  20.    "PRIMARY KEY ( tutorial_id )); ";
  21.  
  22.      mysql_select_db( ' Database TUTORIALS' );
  23. $retval = mysql_query( $sql, $con);
  24. if(! $result )
  25. {
  26.   die('Could not create table: ' . mysql_error());
  27. }
  28. echo "Table has been  created successfully\n";
  29. mysql_close($conn);
  30. ?>
  31. </body>
  32. </html>

 

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!