---[REF]---"style":"heading"---[REF]---
---[SIDEBAR]---
"type":"objectives",
"title":"Learning Objectives",
"text":"After completing this lesson, the successful student will be able to use SQL statements to:
- Create database tables.
- Make changes to database tables.
- Remove tables from a database.
Data types used in SQLite
An example of the syntax used to define the name column on the vendor table with a data type of text is:
CREATE TABLE vendor (
name TEXT
)
#### Column Constraints
You can also add additional constraints on the values can be added to a column. These constaints are enforced by the DBMS. When a user tries to add a new row to the database table that violates one of these constraints, the DBMS prohibits the row from being saved to the table.
The first constraint that can be added to a column is the unique constraint. The unique constraint is applied using the keyword UNIQUE. The unique constraint ensures that each value for that column is different than all of the other values in that column. If a user attempts to add a new row to the table with a duplicate value for that column, the DBMS will prohibit the new record from being added to the table.
---[SIDEBAR]---
"type":"term",
"title":"UNIQUE",
"text":"Constraint added to a column that ensures that all each value in the table for that column is different than all other values for that column."
---[SIDEBAR]---
You can also add a constraint that ensures that a column has a value when a new row is added to the table. This constraint is added using the keywords NOT NULL. This constraint essential makes values for this column required for each row that is added to the table.
---[SIDEBAR]---
"type":"term",
"title":"NOT NULL",
"text":"Constraint added to a column that ensures that a column has a a value when a new row is added to the table."
---[SIDEBAR]---
A column can also be designed as the primary key using a column constraint. This is done using the keywords PRIMARY KEY. Recall that when a column is a primary key, values for that column must be both unique and not null. Most DBMS will also add features to primary key columns. These features are not discussed in this resource.
---[SIDEBAR]---
"type":"term",
"title":"PRIMARY KEY constraint",
"text":"Constrains the values for a column to be both unique and not null. Additional features will likely be added to primary key columns by the DBMS."
---[SIDEBAR]---
An example of the syntax used to define the vendor table with a vendor_id as interger data and the primary key and the name column with a data type of text with the constraint that the name be NOT NULL is:
CREATE TABLE vendor (
vendor_id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)
You can also add additional custom constraints to the columns of a database table. These are added using the keyword CHECK. CHECK constraints create a logical test that the values for a column must satisfy before a new row can be added to a database table. For example, you could create a check constraint to ensure that the values for a new employee's salary are within an appropriate range.
---[SIDEBAR]---
"type":"term",
"title":"CHECK",
"text":"Custom constraint that ensures the values for a column satisfy a logical test before a new row can be added to a table."
---[SIDEBAR]---
### Defining Table Options
After the columns have been defined in the table creation statement, table-level constraints can be added. The two table-level constraints that are primary and foreign keys. Generally, a primary key is designated when the column is defined. However, if multiple columns are used together as a composite primary key, the primary key must be added as a table-level constraint. This is done using the keywords PRIMARY KEY followed by a comma separated list of the fields that make up the composite primary key in parentheses. An example of the syntax used to define the composite primary key with the product_id, sale_id, and product_size columms is:
PRIMARY KEY (product_id, sale_id, product_size)
Foreign keys are also added as table-level constraints. There are three elements to a foreign key constraint. First, the column to be used as the foreign key is identified. This column must exist on the table. Second, the table that the foreign key references is defined. Finally, constaint must also designate what to do if the referenced values on the related table are deleted from the database. The following syntax demonstrates how the museum_id would be designed as a foreign key on the vendor table referencing the museum table:
CREATE TABLE vendor (
vendor_id INTEGER PRIMARY KEY,
...
museum_id INTEGER,
FOREIGN KEY (museum_id) REFERENCES museum ON DELETE SET NULL
)
Notice the set of keywords in the foreign key constraint. The keywords FOREIGN KEY are used to designed the foreign key. The keyword REFERENCES specifies the table that the foreign key relates. ON DELETE SET NULL ensures that if an museum is deleted from the museum table, the values for the corresponding museum_id on the vendor table will be set to NULL. This way the vendor table will not reference an museum that does not exist.
Putting all of these pieces together, the table creation statement is generated. A table creation statement to create the vendor table in the museum database would be:
CREATE TABLE vendor(
vendor_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT NOT NULL,
museum_id INTEGER,
FOREIGN KEY(museum_id) REFERENCES museum ON DELETE SET NULL
);
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:create-vendor-table
---[SQL]---
CREATE TABLE vendor(
vendor_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT NOT NULL,
museum_id INTEGER,
FOREIGN KEY(museum_id) REFERENCES museum ON DELETE SET NULL
);
---[SQL]---
The result of executing the query would be a response from the DMBS that the statement executed without errors. When this happens, the table will be added to the database. Of course at this point there would not be any data in the table. The SQL statements used to add data to the blank table will be discussed in ---[REF]---"style":"link","pageId":"lesson-insert"---[REF]---. If there are errors that occur during the execution of the statement the DBMS will respond with the error statements.
## Deleting Tables
A common error that occurs when attempting to add a table to a database happens when you try to add a table that already exists in the database. If you wish to replace the existing table, you must remove it from the database first. To remove a table from the database, you use the keywords DROP TABLE. The keyword DROP is used to remove objects from the database. The keyword table is used to designate that a table is being removed.
---[SIDEBAR]---
"type":"term",
"title":"DROP",
"text":"The keyword used in a SQL statement to remove an object from the database."
---[SIDEBAR]---
When a table is dropped from the database, the table is completed removed including all of the data stored on the table. The syntax used to remove the vendor table you just created from the database would be:
DROP TABLE vendor;
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:drop-vendor-table
---[SQL]---
DROP TABLE vendor;
---[SQL]---
---[SIDEBAR]---
"type":"caution",
"title":"Removing Database Tables",
"text":"The SQL statement used to remove a table from a database is simple and there is not a command to undo removing a table. Care should be taken when removing tables to prevent accidental deletion and data loss."
---[SIDEBAR]---
## Editing Tables
From time to time, you will need to make changes to an existing database table. The keywords used to change a table are ALTER TABLE. The keyword ALTER is used to change a database object. The syntax for changing a database table is:
---[SIDEBAR]---
"type":"term",
"title":"ALTER",
"text":"The keyword used in a SQL statement to change an object in the database."
---[SIDEBAR]---
ALTER TABLE tablename
*statements that define the changes to be made*
For example, you could add or delete a column from an existing table. The syntax to add a column vendor_phone to an existing table named vendor would be:
ALTER TABLE vendor
ADD vendor_phone TEXT;
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:alter-vendor-add-vendor-phone
---[SQL]---
CREATE TABLE vendor(
vendor_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT NOT NULL,
museum_id INTEGER,
FOREIGN KEY(museum_id) REFERENCES museum ON DELETE SET NULL
);
ALTER TABLE vendor
ADD vendor_phone TEXT;
---[SQL]---
Note that if you tried the DROP statement in the last section, your copy of the vendor table will have been deleted from the database. This is why this example creates a vendor table first. If you did not delete the table, you will receive an error when trying to create the vendor table in this example.
Similarly, the syntax used to change the table and remove the vendor_phone column would be:
ALTER TABLE vendor
DROP vendor_phone;
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:alter-vendor-remove-vendor-phone
---[SQL]---
ALTER TABLE vendor
DROP vendor_phone;
---[SQL]---
Tables can also be altered to define primary and foreign keys after a table is created.
---[SIDEBAR]---
"type":"tip",
"title":"Limitations to Altering Tables",
"text":"Some DBMS, notably SQLite limit what can be done to change a table. Check with the documentation of the DBMS you are using to know what these limitations might be."
---[SIDEBAR]---
## Summary
This lesson described how to write SQL statements to manipulate database tables. Specifically, it described how to add database tables using the CREATE TABLE keywords. When a table is created, the table columns and table-level constraints are also defined. The lesson also described how to remove and edit existing tables in a database.
| Data Type | Description |
|:---------:|--------------------------------------------------------------------------------|
| Integer | Whole numbers |
| Real | Floating point (decimal numbers)values |
| Text | String of text |
| Blob | Blob of data (stored exactly as it was input - for example a file) |
| NULL | NULL values |