Saturday, September 6, 2014

Creation

A database is a container that holds tables and other SQL structures related to those tables

Creating a database
create database <name of the database>;

Describing a database
DESC <name of the database>

Creating a table
CREATE TABLE <name of the table>(<names of columns>)
CREATE TABLE doughnut_list
                   (doughnut_name VARCHAR(10),
                    doughnut_type VARCHAR(6));

CREATE TABLE my_contacts
(
   contact_id INT NOT NULL,
   last_name VARCHAR(30) DEFAULT NULL,
   PRIMARY KEY (contact_id)
);

To avoid inserting unique values for the primary key, set it to auto_increment
CREATE TABLE my_contacts
(
   contact_id INT NOT NULL AUTO_INCREMENT,
   last_name VARCHAR(30) DEFAULT NULL,
   PRIMARY KEY (contact_id)
);

inserting into a table with auto_increment
INSERT INTO my_table VALUES (NULL, 'Keith', 'Tapp');
INSERT INTO my_table VALUES ('', 'Keith', 'Tapp');
INSERT INTO my_table VALUES ('Keith', 'Tapp');
INSERT INTO my_table VALUES (99, 'Keith', 'Tapp');

VARCHAR(10) is a variable

What query has been used to create a table
SHOW CREATE TABLE my_contacts;

Certain columns in the table should always have values
CREATE TABLE my_contacts
             (last_name VARCHAR(30) NOT NULL,
              first_name VARCHAR(20) NOT NULL);

Filling default values
CREATE TABLE blah(cost DEC(3,2) NOT NULL DEFAULT 1.00)

CREATE TABLE interests (
int_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
interest VARCHAR(50) NOT NULL,
contact_id INT NOT NULL,
CONSTRAINT my_contacts_contact_id_fk FOREIGN KEY(contact_id)
REFERENCES my_contacts (contact_id);
)

Dropping a table
DROP TABLE <name of the table>

Inserting values into a table
insert into <name of the table> (<name of columns>) values (<values>)

No comments:

Post a Comment