Tuesday, 12 February 2013

Adding Table and Inserting values


The SQL command used to create a new table in a database typically looks like this:
CREATE TABLE table-name (field-name-1 field-type-1 modifiers,
field-name-2 field-type-2 modifiers, ... , field-name-n
field-type-n modifiers)

The table name cannot contain spaces, slashes, or periods; other than this, any
character is fair game. Each table (and the data it contains) is stored as a set of three
files in your MySQL data directory.

Here’s a sample command to create the members table in the example you saw a
couple sections back:
mysql> CREATE TABLE members (member_id int(11) NOT NULL auto_increment,
fname varchar(50) NOT NULL, lname varchar(50) NOT NULL, tel varchar(15),
email varchar(50) NOT NULL, PRIMARY KEY (member_id));



Once you’ve created a table, it’s time to begin entering data into it, and the SQL command
to accomplish this is the INSERT command. The syntax of the INSERT command is as
follows:
INSERT into table-name (field-name-1, field-name2, field-name-n)
VALUES(value-1, value-2, value-n)

Here’s an example:
mysql> INSERT INTO members (member_id, fname, lname, tel, email)
VALUES (NULL, 'John', 'Doe', '1234567', 'jdoe@somewhere.com');

You could also use the abbreviated form of the INSERT statement, in which field
names are left unspecified:
mysql> INSERT INTO members VALUES (NULL, 'John', 'Doe', '1234567',
'jdoe@somewhere.com');

Here’s the flip side: by specifying field names in the INSERT statement, I have
the flexibility of inserting values in any order I please. Because of this, the following
statements are equivalent:
mysql> INSERT INTO members (member_id, fname, lname, tel, email)
VALUES (NULL, 'John', 'Doe', '1234567', 'jdoe@somewhere.com');
and
mysql> INSERT INTO members (fname, lname, email, tel, member_id)
VALUES ('John', 'Doe', 'jdoe@somewhere.com', '1234567', NULL);

Fields that are not specified will automatically be set to their default values.


Related Posts:

  • A Brief History and Overview of SQL SQL began life as SEQUEL, the Structured English Query Language, a component of an IBM research project called System/R. System/R was a prototype of the first relational database system; it was created at IBM’s San Jose lab… Read More
  • Understanding an RDBMS Every database is composed of one or more tables. These tables, which structure data into rows and columns, are what lend organization to the data. Here’s an example of what a typical table looks like: As you can … Read More
  • Adding Table and Inserting values The SQL command used to create a new table in a database typically looks like this: CREATE TABLE table-name (field-name-1 field-type-1 modifiers, field-name-2 field-type-2 modifiers, ... , field-name-n field-type-n modifier… Read More

0 comments:

Post a Comment