Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble understanding SQL (Oracle) create table code

I am aware of Oracle's create table syntax

CREATE TABLE MyTable(
   id int primary key,
   ...
);

This will create a table called MyTable with an int primary key. So, nothing new here.

but I am having difficulties understanding the following query:

CREATE TABLE departament (
   cod_dept    INTEGER CONSTRAINT dept_key PRIMARY KEY,
   dept_name CHAR(15) NOT NULL,
   admission    DATE      NOT NULL,
   localization CHAR(20))

When I look up on Oracle's SQL Developer software on departement's table, I can see 4 columns: cod_dept, dept_name, admission and localization. On the constraints tab, I can also see dept_key, but I am confused as to what this might mean. What is dept_key purpose here?

Edit

Ok, seems it is a way to define the name of the constraint you're adding to the table. My next question is why don't you just call it the same name as the primary key column? From what I've seen it seems Oracle by default just creates a random name for the constraint!

Thanks

like image 468
devoured elysium Avatar asked Jun 17 '26 18:06

devoured elysium


2 Answers

When you write id int primary key, Oracle will create a primary key constraint to ensure uniqueness of primary key values. All constraints have names, so in this case Oracle assigns an autogenerated name to this constraint. But you can set a name of this constraint explicitly using the CONSTRAINT syntax:

cod_dept    INTEGER CONSTRAINT dept_key PRIMARY KEY

This name may be used later to refer to the constraint, for example, to delete or modify it:

ALTER TABLE department DROP CONSTRAINT dept_key;

EDIT: Constraint names are unique across the schema, so Oracle can't just use the name of primary key column as a constraint name.

like image 155
axtavt Avatar answered Jun 19 '26 14:06

axtavt


Primary keys can be explicitly be named. dept_key is just a name.

like image 29
Detect Avatar answered Jun 19 '26 15:06

Detect