Create Table Statement
Tables are the basic structure where data is stored in the database. Given that in most cases, there is no way for the database vendor to know ahead of time what your data storage needs are, chances are that you will need to create tables in the database yourself. Many database tools allow you to create tables without writing SQL, but given that tables are the container of all the data, it is important to include the CREATE TABLE syntax in this tutorial. Before we dive into the SQL syntax for CREATE TABLE, it is a good idea to understand what goes into a table. Tables are divided into rows and columns. Each row represents one piece of data, and each column can be thought of as representing a component of that piece of data. So, for example, if we have a table for recording customer information, then the columns may include information such as First Name, Last Name, Address, City, Country, Birth Date, and so on. As a result, when we specify a table, we include the column headers and the data types for that particular column. So what are data types? Typically, data comes in a variety of forms. It could be an integer (such as 1), a real number (such as 0.55), a string (such as 'sql'), a date/time expression (such as '2000-JAN-25 03:22:22'), or even in binary format. When we specify a table, we need to specify the data type associated with each column (i.e., we will specify that 'First Name' is of type char(50) - meaning it is a string with 50 characters). One thing to note is that different relational databases allow for different data types, so it is wise to consult with a database-specific reference first. The SQL syntax for CREATE TABLE is CREATE TABLE "table_name" ("column 1" "data_type_for_column_1", "column 2" "data_type_for_column_2", ... ) So, if we are to create the customer table specified as above, we would type in CREATE TABLE customer (First_Name char(50), Last_Name char(50), Address char(50), City char(50), Country char(25), Birth_Date date)
Create View Statement
Views can be considered as virtual tables. Generally speaking, a table has a set of definition, and it physically stores the data. A view also has a set of definitions, which is build on top of table(s) or other view(s), and it does not physically store the data. The syntax for creating a view is as follows: CREATE VIEW "VIEW_NAME" AS "SQL Statement" "SQL Statement" can be any of the SQL statements we have discussed in this tutorial. Let's use a simple example to illustrate. Say we have the following table: TABLE Customer (First_Name char(50), Last_Name char(50), Address char(50), City char(50), Country char(25), Birth_Date date) and we want to create a view called V_Customer that contains only the First_Name, Last_Name, and Country columns from this table, we would type in, CREATE VIEW V_Customer AS SELECT First_Name, Last_Name, Country FROM Customer Now we have a view called V_Customer with the following structure: View V_Customer (First_Name char(50), Last_Name char(50), Country char(25)) We can also use a view to apply joins to two tables. In this case, users only see one view rather than two tables, and the SQL statement users need to issue becomes much simpler. Let's say we have the following two tables: Table Store_Information store_name Sales Date Los Angeles $1500 Jan-05-1999
San Diego
$250 Jan-07-1999
Los Angeles
$300 Jan-08-1999
Boston
$700 Jan-08-1999
Table Geography region_name store_name East
Boston
East
New York
West
Los Angeles
West
San Diego
and we want to build a view that has sales by region information. We would issue the following SQL statement: CREATE VIEW V_REGION_SALES AS SELECT A1.region_name REGION, SUM(A2.Sales) SALES FROM Geography A1, Store_Information A2 WHERE A1.store_name = A2.store_name GROUP BY A1.region_name This gives us a view, V_REGION_SALES, that has been defined to store sales by region records. If we want to find out the content of this view, we type in, SELECT * FROM V_REGION_SALES Result: REGION SALES East $700 West $2050
Create Index Statement Indexes help us retrieve data from tables quicker. Let's use an example to illustrate this point: Say we are interested in reading about how to grow peppers in a gardening book. Instead of reading the book from the beginning until we find a section on peppers, it is much quicker for us to go to the index section at the end of the book, locate which pages contain information on peppers, and then go to these pages directly. Going to the index first saves us time and is by far a more efficient method for locating the information we need. The same principle applies for retrieving data from a database table. Without an index, the database system reads through the entire table (this process is called a 'table scan') to locate the desired information. With the proper index in place, the database system can then first go through the index to find out where to retrieve the
data, and then go to these locations directly to get the needed data. This is much faster. Therefore, it is often desirable to create indexes on tables. An index can cover one or more columns. The general syntax for creating an index is: CREATE INDEX "INDEX_NAME" ON "TABLE_NAME" (COLUMN_NAME) Let's assume that we have the following table, TABLE Customer (First_Name char(50), Last_Name char(50), Address char(50), City char(50), Country char(25), Birth_Date date) and we want to create an index on the column Last_Name, we would type in, CREATE INDEX IDX_CUSTOMER_LAST_NAME on CUSTOMER (Last_Name) If we want to create an index on both City and Country, we would type in, CREATE INDEX IDX_CUSTOMER_LOCATION on CUSTOMER (City, Country) There is no strict rule on how to name an index. The generally accepted method is to place a prefix, such as "IDX_", before an index name to avoid confusion with other database objects. It is also a good idea to provide information on which table and column(s) the index is used on.
Alter Table Statement
Once a table is created in the database, there are many occasions where one may wish to change the structure of the table. Typical cases include the following: • • • •
Add a column Drop a column Change a column name Change the data type for a column
Please note that the above is not an exhaustive list. There are other instances where ALTER TABLE is used to change the table structure, such as changing the primary key specification.
The SQL syntax for ALTER TABLE is ALTER TABLE "table_name" [alter specification] [alter specification] is dependent on the type of alteration we wish to perform. For the uses cited above, the [alter specification] statements are: • • • •
Add a column: ADD "column 1" "data type for column 1" Drop a column: DROP "column 1" Change a column name: CHANGE "old column name" "new column name" "data type for new column name" Change the data type for a column: MODIFY "column 1" "new data type"
Let's run through examples for each one of the above, using the "customer" table created in the CREATE TABLE section: Table customer Column Name Data Type First_Name
char(50)
Last_Name
char(50)
Address
char(50)
City
char(50)
Country
char(25)
Birth_Date
date
First, we want to add a column called "Gender" to this table. To do this, we key in: ALTER table customer add Gender char(1) Resulting table structure: Table customer Column Name Data Type First_Name
char(50)
Last_Name
char(50)
Address
char(50)
City
char(50)
Country
char(25)
Birth_Date
date
Gender
char(1)
Next, we want to rename "Address" to "Addr". To do this, we key in,
ALTER table customer change Address Addr char(50) Resulting table structure: Table customer Column Name Data Type First_Name
char(50)
Last_Name
char(50)
Addr
char(50)
City
char(50)
Country
char(25)
Birth_Date
date
Gender
char(1)
Then, we want to change the data type for "Addr" to char(30). To do this, we key in, ALTER table customer modify Addr char(30) Resulting table structure: Table customer Column Name Data Type First_Name
char(50)
Last_Name
char(50)
Addr
char(30)
City
char(50)
Country
char(25)
Birth_Date
date
Gender
char(1)
Finally, we want to drop the column "Gender". To do this, we key in, ALTER table customer drop Gender Resulting table structure: Table customer Column Name Data Type First_Name
char(50)
Last_Name
char(50)
Addr
char(30)
City
char(50)
Country
char(25)
Birth_Date
date
Primary Key
A primary key is used to uniquely identify each row in a table. It can either be part of the actual record itself , or it can be an artificial field (one that has nothing to do with the actual record). A primary key can consist of one or more fields on a table. When multiple fields are used as a primary key, they are called a composite key. Primary keys can be specified either when the table is created (using CREATE TABLE) or by changing the existing table structure (using ALTER TABLE). Below are examples for specifying a primary key when creating a table: MySQL: CREATE TABLE Customer (SID integer, Last_Name varchar(30), First_Name varchar(30), PRIMARY KEY (SID)); Oracle: CREATE TABLE Customer (SID integer PRIMARY KEY, Last_Name varchar(30), First_Name varchar(30)); SQL Server: CREATE TABLE Customer (SID integer PRIMARY KEY, Last_Name varchar(30), First_Name varchar(30)); Below are examples for specifying a primary key by altering a table: MySQL: ALTER TABLE Customer ADD PRIMARY KEY (SID); Oracle: ALTER TABLE Customer ADD PRIMARY KEY (SID);
SQL Server: ALTER TABLE Customer ADD PRIMARY KEY (SID); Note: Before using the ALTER TABLE command to add a primary key, you'll need to make sure that the field is defined as 'NOT NULL' -- in other words, NULL cannot be an accepted value for that field.
Foreign Key A foreign key is a field (or fields) that points to the primary key of another table. The purpose of the foreign key is to ensure referential integrity of the data. In other words, only values that are supposed to appear in the database are permitted. For example, say we have two tables, a CUSTOMER table that includes all customer data, and an ORDERS table that includes all customer orders. The constraint here is that all orders must be associated with a customer that is already in the CUSTOMER table. In this case, we will place a foreign key on the ORDERS table and have it relate to the primary key of the CUSTOMER table. This way, we can ensure that all orders in the ORDERS table are related to a customer in the CUSTOMER table. In other words, the ORDERS table cannot contain information on a customer that is not in the CUSTOMER table. The structure of these two tables will be as follows: Table CUSTOMER column name Characteristic SID
Primary Key
Last_Name First_Name Table ORDERS column name
characteristic
Order_ID
Primary Key
Order_Date Customer_SID Foreign Key Amount
In the above example, the Customer_SID column in the ORDERS table is a foreign key pointing to the SID column in the CUSTOMER table. Below we show examples of how to specify the foreign key when creating the ORDERS table: MySQL: CREATE TABLE ORDERS (Order_ID integer, Order_Date date, Customer_SID integer, Amount double, Primary Key (Order_ID), Foreign Key (Customer_SID) references CUSTOMER(SID)); Oracle: CREATE TABLE ORDERS (Order_ID integer primary key, Order_Date date, Customer_SID integer references CUSTOMER(SID), Amount double); SQL Server: CREATE TABLE ORDERS (Order_ID integer primary key, Order_Date datetime, Customer_SID integer references CUSTOMER(SID), Amount double); Below are examples for specifying a foreign key by altering a table. This assumes that the ORDERS table has been created, and the foreign key has not yet been put in: MySQL: ALTER TABLE ORDERS ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID); Oracle: ALTER TABLE ORDERS ADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID); SQL Server: ALTER TABLE ORDERS ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);
Drop Table Statement
Sometimes we may decide that we need to get rid of a table in the database for some reason. In fact, it would be problematic if we cannot do so because this could create a maintenance nightmare for the DBA's. Fortunately, SQL allows us to do it, as we can use the DROP TABLE command. The syntax for DROP TABLE is DROP TABLE "table_name" So, if we wanted to drop the table called customer that we created in the CREATE TABLE section, we simply type DROP TABLE customer.
Truncate Table Statement
Sometimes we wish to get rid of all the data in a table. One way of doing this is with DROP TABLE, which we saw in the last section. But what if we wish to simply get rid of the data but not the table itself? For this, we can use the TRUNCATE TABLE command. The syntax for TRUNCATE TABLE is TRUNCATE TABLE "table_name" So, if we wanted to truncate the table called customer that we created in SQL CREATE, we simply type, TRUNCATE TABLE customer