Handout 5 - Working With Tables in SQL
Handout 5 - Working With Tables in SQL
doc
1 Overview
This handout deals with tables in SQL and in SQL Server. We will look at how to create and
drop (delete) tables using SQL scripts and using the SQL Server Enterprise Manager.
So, to create a table named Projects, with columns for Project ID, Project Name and the
Employee ID of the Manager, the following script can be run.
CREATE TABLE Projects
(
ProjectID int NOT NULL Identity (1,1),
ProjectName varchar(50) NOT NULL,
ManagerEmpID int
)
3 Constraints
When a table is created, there are a number of types of constraint that can be applied to the
table. Constraints are used to enforce data integrity in a relational database. They define rules
for the values that are allowed in table columns. The types of constraint that can be defined in
SQL Server are described below.
Page 1 of 10
507375724.doc
For example, in the SQL Server pubs database – pub_id is the Primary Key in the pubs table.
Pub_id is the Foreign Key in the titles table.
A Foreign Key constraint enforces the referential integrity of the foreign key relationship.
The constraint is defined on the child or detail table. It identifies the table and column(s) that
hold the related Primary Key or Unique values.
When a Foreign Key constraint is defined on a table, only values that exist in the related
Primary Key/Unique column(s) can be entered into the foreign key column.
The referential integrity of the data can be controlled by specifying actions to take if an
attempt is made to delete or update the related rows in the parent/master table.
The possible actions are:
No action – do nothing, and the attempted deletion or insertion fails and reports an
error
Cascade – delete or update the rows in the child/detail table that point to the row
being deleted or updated.
The use of No Action or Cascade depends on the circumstances. In some cases, it is not a
good idea to do a Cascading delete – for example, in the Pubs database there is a foreign key
constraint imposed on the pub_id column in the titles table, referencing publishers.pub_id. If
a publisher were to be deleted, a cascading delete would result in all titles associated with that
publisher also being deleted. This could be a problem, if it was not the intention to delete the
titles. Therefore, it is generally better to leave the default behaviour of 'no action' for foreign
key updates and deletes.
1.3 Unique
A Unique constraint enforces the uniqueness of values in a column or set of columns in the
table.
NULLs are allowed in the column(s) referenced by a UNIQUE constraint.
A table can have more than one Unique constraint.
Page 2 of 10
507375724.doc
1.4 Check
A Check constraint enforces domain integrity by limiting the set of values that can be entered
into a column. The constraint defines a logical expression that returns a boolean value (True
or False). The logical expression checks the entered value against some comparison criteria
and returns true or false. If the return value is true, then the value can be entered. If it is false,
then the value cannot be entered and an error (violation of the constraint) is returned.
For example:
To validate that the value entered in the titles.price field is a positive value:
price > 0
To validate that an employee's salary is greater than 1000 and less than 100,000:
1000 <= salary AND salary <= 100000
When a constraint needs to reference two columns (e.g. a Primary Key or Unique constraint
that consists of two columns) then it is necessary to define the constraint as a table constraint.
When it is defined as a column constraint, it references only that column.
However, if all constraints are defined using the table constraint syntax, then it is easier to see
all the constraints on the table as they are grouped together after the column definitions.
The syntax for the CREATE TABLE statement with column and table constraints is as
follows.
ColumnConstraint:
[CONSTRAINT constraint_name]
| UNIQUE
| PRIMARY KEY
| [FOREIGN KEY] REFERENCES TableName [( ColumnName )] [ actions ]
TableConstraint:
[CONSTRAINT constraint_name]
| UNIQUE ( column-name, ... )
| PRIMARY KEY ( column-name, ... )
| CHECK ( condition )
| ForeignKeyConstraint
Page 3 of 10
507375724.doc
ForeignKeyConstraint:
[CONSTRAINT constraint_name]
FOREIGN KEY [(column-name, ... )]
. . . REFERENCES table-name [(column-name, ... )]
. . . [ Actions ]
Actions:
Notes:
The keyword CONSTRAINT and a name for the constraint are optional – if you do
not supply a name for a constraint, SQL Server will generate a unique name
automatically. It is better to supply your own names, as you can name the constraints
in ways that identify what their functions are e.g. pk_employees, pk_departments,
fk_employee_dept, check_emp_salary. Constraint names have to be unique in a
database – SQL Server will return an error if you duplicate a name.
Primary Key, Unique and Foreign Key constraints can reference more than one
column.
When creating a Foreign Key constraint, the default is NO ACTION, if ON UPDATE
and ON DELETE are not included in the definition.
Some examples:
To create a table named Departments, with columns for Department ID and Name, with types
integer and varying character, respectively; Department ID is the primary key and should
have automatically generated sequential ID values; Names should be unique:
The above statement uses table constraints. The same table can be created using column
constraints, as follows:
CREATE TABLE DEPARTMENTS
(
DepartmentID int not null identity CONSTRAINT pk_departments primary key,
DepartmentName varchar(50) not null DEFAULT 'unknown' CONSTRAINT unique_dept_name
unique (DepartmentName)
)
To create a table named Employees, with columns for Employee ID, Name, Father's Name,
Phone number, Salary, Department ID; Employee ID is the primary key and should have
automatically generated sequential ID values; to ensure valid salaries are entered, the values
should be between 100 and 100,000; the Department ID can only be one of the values in the
Department table.
Page 4 of 10
507375724.doc
There are also dependencies between tables, when foreign key constraints are created. If a
foreign key constraint references a table, that table cannot be dropped until the foreign key
constraint is dropped.
A constraint is automatically dropped when the table that 'owns' it is dropped.
If the Foreign Key constraint on the Employees table still exists, the execution of this
statement will result in an error like this:
Server: Msg 3726, Level 16, State 1, Line 1
Could not drop object 'departments' because it is referenced by a FOREIGN KEY constraint.
In that case, the referencing Foreign Key constraint needs to be dropped. This can be done by
dropping the table that 'owns' the constraint i.e. the Employees table:
6 Altering Tables
If you wish to make a change to a table after it has been created, you can do so by using the
ALTER TABLE statement.
Page 5 of 10
507375724.doc
This is often preferable to dropping a table and then re-creating it, as it does not involve
deleting the data in the table.
The ALTER TABLE statement can be used to alter, add or drop individual columns and
constraints in the table.
(Remember that the | symbol means 'or' when describing the syntax of a statement, and the []
brackets indicate an optional element.)
In the above, the column_definition and table_constraint syntax are as described for the
Create Table statement (in section 4 above).
Some examples:
To drop the foreign key constraint that relates Employees.DepartmentID to
Departments.DepartmentID:
ALTER TABLE Employees
DROP CONSTRAINT fk_employees_deptid
You could then proceed to drop the Departments table, as the foreign key referencing it no
longer exists. When you want to add the foreign key constraint back in, run the following:
To add a new column to the Departments table, to hold the Employee ID of the employee
who is the manager of the Department:
ALTER TABLE Departments
ADD EmpManagerID int
To add a foreign key constraint to ensure that only existing EmployeeID values are entered in
this new field:
ALTER TABLE Departments
ADD CONSTRAINT fk_dept_emp_mgrid foreign key (EmpManagerID) references
Employees (EmployeeID)
The SQL Server Enterprise Manager provides a graphical interface for working with tables.
Some of the things you can do are as follows. Most of these tasks can also be achieved by
executing SQL in the Query Analyzer – where this is possible, both methods are given here.
Page 6 of 10
507375724.doc
You can also view all the rows in the Enterprise Manager. To do this:
- Find the table under the Tables group in the database
- Select the table and right-click
- Choose 'Return all rows'
- A window displaying all the data in the table will open up
If you wish to view a subset of rows and/or columns, you can type a SQL query:
- Click the 'Show/hide SQL pane' button in the toolbar – this is the icon that has the
word 'SQL' on it
- This will display a pane in which you can type a query – the initial query is 'Select *
from table_name', as it is displaying all rows and all columns.
- Change the query
- Click the 'Run' button in the toolbar – this is the icon that looks like a large red
exclamation mark (!).
If the table you are viewing has many thousands of rows, it can take some time to return all
the rows when you choose the 'Return all rows' option. In that case, you can choose the
option 'Return top…'. With this option, you can specify the number of rows to display.
You can also enter data into the table when viewing the rows in this way in the Enterprise
To see the design information for a table in Query Analyzer, run the following SQL:
sp_help table_name
sp_help is a system built-in stored procedure – it takes the table name as a parameter and
returns the table definition information. We will learn more about stored procedures later in
the course.
The resulting window is a data-entry sheet on which you can enter the definition details for
the table columns. For each column, you enter the Column Name, Data Type, Length and
check if it allows nulls or not.
The tab under the data-entry sheet allows you to specify if the current column is an identity
field or not, and to specify the seed an increment for the identity.
To specify the primary key column(s) for the table, select the column(s) and click the yellow
key icon in the toolbar. The key column(s) will then show a key icon to the left of the data-
entry sheet.
When you have finished entering the table definitions, click the 'Save' button (the floppy disk
icon) in the toolbar to save the table.
Page 7 of 10
507375724.doc
The resulting window is as described for modifying a table – enter the column definitions,
primary key and identity information and save.
If you simply wish to view or copy the script for a table, but do not want to save it, you can
do the following:
Page 8 of 10
507375724.doc
If you copied the script, it will remain in the clipboard so you can paste it into another
location e.g. into the Query Analyzer editor pane.
For example, the script generated for the Employees table created as an example in this
handout is as follows. Note that ALTER TABLE statements are used to add the constraints –
so the script does not match exactly the one that was used to create the table. Also note that
the script first checks to see if the table exists – if it does, then it is dropped before being
created.
The 'GO' statement is a SQL Server (not SQL standard) command used to separate batches of
statements – all the statements up to the 'GO' are executed before the next batch.
Page 9 of 10
507375724.doc
Query Analyzer – if you write the scripts yourself, use the File|Save menu option to
save the queries. When doing this, ensure that the cursor is in the editor pane (not in
the results pane – as this would save only the query results currently displayed).
Enterprise Manager – if you created the tables, or modified them, using the Enterprise
Manager, make sure you script them (as described in section 1.9 above) and save the
scripts. Ensure that all keys, constraints etc are scripted by checking the options on the
Options tab.
It is good practice to always maintain creation scripts for the objects in your database, so that
the database can be recreated if necessary. It also means you can reuse the scripts.
You should become familiar with creating, altering and dropping tables using SQL rather
than the Enterprise Manager, as you will then be able to create tables on other RDBMS
packages also, using SQL.
Page 10 of 10