Table Creation Examples

Here is a simple example of the SQL used to create a couple tables, populate them, create a view, and grant access to view them.

Create the two tables:

create table name
(
id number not null,
first_name varchar2(30),
last_name varchar2(30) not null,
constraint pk_name primary key (id)
);

create table office_location
(
name_id number not null,
room_number varchar2(6 byte),
building varchar2(20 byte),
constraint person_exists foreign key(name_id)
references name,
constraint room_number_check check (room_number between 0 and 799)
);

Insert some values into each:

insert into name (id, first_name, last_name)
values (1, 'Jon', 'Emmons');

insert into name (id, first_name, last_name)
values (2, 'Matt', 'Batchelder');

insert into name (id, first_name, last_name)
values (3, 'Zach', 'Tirrell');

insert into name (id, first_name, last_name)
values (4, 'Jon', 'Graton');

insert into office_location (name_id, room_number, building)
values (1, '334', 'Hyde');

insert into office_location (name_id, room_number, building)
values (2, '334', 'Hyde');

insert into office_location (name_id, room_number, building)
values (3, '222', 'Hyde');

insert into office_location (name_id, room_number, building)
values (4, '333', 'Hyde');

Extract some meaningful data with a simple join:

select first_name, last_name, building, room_number
from name, office_location
where id=name_id;

Create a view based on that join:

create view name_office as
(
select first_name, last_name, building, room_number
from name, office_location
where id=name_id
);

Select from our new view:

select * from name_office;

Grant access to jemmons to the tables and view (note that you do not have to grant access to the underlying tables for a user to be able to select from the view):

grant select on name to jemmons;

grant select on office_location to jemmons;

grant select on name_office to jemmons;

Technorati tags: , , ,

3 thoughts on “Table Creation Examples”

  1. To add a constraint to a table that already exists the syntax should look like this:

    alter table name add (constraint pk_name primary key (id));

    The part in the parens should look the same as the constraint line in the create table command.

  2. Out of curiousity, is there a GUI program that allows you to add tables and stuff? Sort of like a cross between VB and MS Access? So, you can create tables and stuff with a program similar to MS Excel, but build a GUI that works similar to VB, but is SQL compliant?

  3. There are some options for GUIs. TOAD (Tool for Oracle Application Developers) is one of the better ones, but is moderately expensive. From my experience you’ll still want to know the bare-bones way of doing things in order to tweak and troubleshoot problems.

    Of course other database management systems have other products. MySQL has quite a few options, most of which are web-based.

Leave a Reply

Your email address will not be published. Required fields are marked *