Handout 5 - Working With Tables in SQL

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 10

507375724.

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.

2 Creating Tables – Basic SQL Syntax


Tables are the main unit of storage in a relational database. In relational database
terminology, a table is also known as a relation.
In SQL, a table is created using the DDL statement CREATE TABLE. This statement is
supported by SQL Server and other RDBMS packages, with each including its own
variations.

The basic syntax for this statement is as follows:

CREATE TABLE TableName


(
| ColumnDefinition |,

)

The syntax for a ColumnDefinition is:

column-name data-type [ NOT NULL ] [ DEFAULT DefaultValue ] [IDENTITY [(seed,increment)]

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
)

The parts of the column definition are as follows:


 data-type – specifies the SQL data type for the column
 NOT NULL – indicates that the column cannot accept NULL values (this is required
for a Primary Key or a Unique column)
 DEFAULT – specifies a default value for the column, used when a row is inserted and
no value is provided for the column
 IDENTITY – this is a property that can only be applied to a column of data type
Integer; it is similar to the MS Access Auto-number field type. The column is
automatically populated with a sequentially increasing number. The seed is the first
value for the column and the increment is the amount to increase the value by for each
new row. If the seed and increment are not specified, the default values are 1 and 1.

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

1.1 Primary Key


A Primary Key constraint identifies the column or set of columns whose values uniquely
identify a row in a table.
When a Primary Key constraint is defined on a table, SQL Server does not allow any two
rows in the table to have the same value in the Primary Key column or the same set of values
in the set of columns that make up the Primary Key.
Also, the column(s) in a Primary Key cannot have NULL values in it (so these columns
should have the NOT NULL directive in the column definition).
A table can have only one Primary Key.

1.2 Foreign Key


A Foreign Key in a table is a column or set of columns in a table that establishes a link, or
relationship, between the data in the two tables. A Foreign Key basically creates a parent-
child or master-detail relationship between two tables. The relationship is created between a
Primary Key or Unique column in the parent or master table and the Foreign Key column in
the child or detail table.

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

4 Creating tables with constraints


All of the above types of constraint can be defined within the CREATE TABLE statement.

They can be created in two places –


a) as part of a column definition – called a column constraint
b) after the column definitions – called a table constraint

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.

CREATE TABLE [creator.]TableName


(
| ColumnDefinition [ ColumnConstraint … ] |,

)| TableConstraint

The different parts are defined below:

ColumnConstraint:
[CONSTRAINT constraint_name]
| UNIQUE
| PRIMARY KEY
| [FOREIGN KEY] REFERENCES TableName [( ColumnName )] [ actions ]

| CHECK ( condition ) <= enforce validation

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:

[ ON UPDATE DoAction] [ ON DELETE DoAction ]


DoAction:
| CASCADE
| NO ACTION

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:

CREATE TABLE DEPARTMENTS


(
DepartmentID int not null identity,
DepartmentName varchar(50) not null DEFAULT 'unknown'
CONSTRAINT pk_department primary key (DepartmentID),
CONSTRAINT unique_dept_name unique (DepartmentName)
)

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

CREATE TABLE Employees (


EmployeeID int not null identity,
Name varchar(30) not null default 'unknown',
FathersName varchar(30) not null default 'unknown',
Phone varchar(20) ,
DepartmentID int ,
Salary decimal (8,2)

CONSTRAINT pk_employees_empid primary key (EmployeeID),


CONSTRAINT fk_employees_deptid foreign key (DepartmentID) references Departments
(DepartmentID),
CONSTRAINT check_employees_salary check (100<= Salary AND Salary <= 100000)
)

5 Dropping (Deleting) Tables


It is also possible to drop (or delete) a table using SQL.
If you are running the queries above, you might find that you want to drop and recreate one
or both tables because you have to make changes to the definitions.
The DROP statement should be used with caution as it drops all the data in the table. If a
table already has data in it, you should ensure that the data is not required or has been backed
up or can be recreated (e.g. by running saved insert scripts).

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.

The SQL statement to drop a table is as follows:


DROP TABLE table_name

So, for example, to drop the Departments table in your database:


DROP TABLE Departments

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:

DROP TABLE Employees

After dropping Employees, the Departments table can be dropped.

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.

The syntax is:


ALTER TABLE table_name
ADD column_definition ,…
| ADD table_constraint
| DROP [CONSTRAINT] constraint_name
| DROP COLUMN column_name,…

(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:

ALTER TABLE Employees


ADD CONSTRAINT fk_employees_deptid foreign key (DepartmentID) references Departments
(DepartmentID)

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)

7 Working with Tables in SQL Server Enterprise Manager

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.

1.5 Viewing & Entering rows in a table


To view the rows in a table, you can run a query to select all the rows in the Query Analyzer:
SELECT * FROM table_name

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

1.6 Viewing the table design


To view the design (or definition) in Enterprise Manager, simply double-click on the table.
The resulting window shows the columns, along with the data-type, size, nulls setting and
default value for each column.
It also indicates the primary key column (by a key icon in the Key column opposite the key
column(s)) and the identity field, if there is one (by a check in the ID column opposite the
identity column).

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.

1.7 Modifying the table design


To modify the design of the table in Enterprise Manager:
- Select the table and right-click
- Choose 'Design Table'

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

1.8 Creating a new table


To create a new table in Enterprise Manager:
- Select the Tables group in the database, or any table in the database
- Right-click and choose 'New table…'

The resulting window is as described for modifying a table – enter the column definitions,
primary key and identity information and save.

1.9 Scripting a Table


In the Enterprise Manager, you can automatically generate the SQL script for a table.
This is useful as a learning tool, to view the scripts for already existing tables, and also if you
need to create tables similar to existing tables.
To do this:
- Select a table in the database
- Right-click and choose 'All Tasks…'
- Choose 'Generate SQL Script…'
- The resulting window has three tabs – General, Formatting, Options
- The General tab shows the table that will be scripted
- Do not make any changes to the Formatting tab
- Click the Options tab
- In the 'Table Scripting Options', check the checkbox for 'Primary keys, Foreign keys,
defaults and check constraints' – this is to include these objects in the script
- Click OK
- The 'Save as…' dialog appears – choose where you want to save the script to and
enter a name for the script (SQL script files usually have a .sql extension, but they are
simply text files so they can be saved as .txt also).
- Click OK
- A progress bar appears with the label 'Scripting in progress'
- When scripting is complete, a message 'Scripting completed successfully' appears –
click OK on this message.
- You will find the script in the location and file you specified it to be saved in.

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:

- Select a table in the database


- Right-click and choose 'All Tasks…'
- Choose 'Generate SQL Script…'
- Click the Options tab
- In the 'Table Scripting Options', check the checkbox for 'Primary keys, Foreign keys,
defaults and check constraints' – this is to include these objects in the script
- Click on the General tab
- Click the Preview button
- A progress bar will appear while the script is being generated
When it is complete, it is displayed
- If you want to copy the script, click the Copy button
- When you are finished viewing the script, click the Close button
- This will return you to the General tab
- Click Cancel to exit.

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.

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Employees]') and


OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Employees]
GO

CREATE TABLE [dbo].[Employees] (


[EmployeeID] [int] IDENTITY (1, 1) NOT NULL ,
[Name] [varchar] (30) COLLATE Latin1_General_CI_AS NOT NULL ,
[FathersName] [varchar] (30) COLLATE Latin1_General_CI_AS NOT NULL ,
[Phone] [varchar] (20) COLLATE Latin1_General_CI_AS NULL ,
[DepartmentID] [int] NULL ,
[Salary] [float] NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Employees] WITH NOCHECK ADD


CONSTRAINT [DF__Employees__Name__2BFE89A6] DEFAULT ('unknown') FOR
[Name],
CONSTRAINT [DF__Employees__Fathe__2CF2ADDF] DEFAULT ('unknown') FOR
[FathersName],
CONSTRAINT [pk_employees_empid] PRIMARY KEY CLUSTERED
(
[EmployeeID]
) ON [PRIMARY] ,
CONSTRAINT [check_employees_salary] CHECK (100 <= [Salary] and [Salary] <=
100000)
GO

ALTER TABLE [dbo].[Employees] ADD


CONSTRAINT [fk_employees_deptid] FOREIGN KEY
(
[DepartmentID]
) REFERENCES [dbo].[DEPARTMENTS] (
[DepartmentID]
)
GO

8 Saving Table Scripts


When you create tables in a database, you should make a habit of saving the scripts for the
tables so that they can be reproduced if necessary e.g. if the database becomes corrupted or is
deleted accidentally.
To do this, make sure you save the SQL scripts for the tables by one of the following
methods:

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

You might also like