Created
Nov 20, 2025
Last Modified
4 months ago

Assignment 7 (SQL / DDL / Constraints)

SQL / DDL / Constraints

DDL Commands

These commands modify the structure of the database.

  • CREATE – create tables, views, etc.

  • ALTER – modify existing table structure.

  • DROP – delete table or column.

  • RENAME – rename table or column.

  • TRUNCATE – remove all rows quickly.


Constraints

Used to enforce rules on table columns.

Constraint

Meaning

PRIMARY KEY

Unique + Not Null

FOREIGN KEY

Ensures reference to another table

UNIQUE

No duplicate values

NOT NULL

Value cannot be empty

CHECK

Restricts range/value

DEFAULT

Provides a default value


📌 USER_CONSTRAINTS

To view constraints applied to your tables:

sql
SELECT constraint_name, constraint_type, table_name 
FROM user_constraints;

📝 Assignment – Clean & Complete Solutions

Create The emp_new table

Column name

Data Type

Size

ID

Number

7

Last_Name

Varchar2

25

First_Name

Varchar2

25

Dept_id

Number

7

Create the dept table

Column name

Data type

Size

Dept_id

Number

10

Dname

Varchar2

20


1️⃣ Create emp_new table

sql
CREATE TABLE emp_new (
    id        NUMBER(7),
    last_name VARCHAR2(25),
    first_name VARCHAR2(25),
    dept_id   NUMBER(7)
);

2️⃣ Create dept table

sql
CREATE TABLE dept (
    dept_id NUMBER(10),
    dname   VARCHAR2(20)
);

3️⃣ Modify emp_new: increase last_name by 50

sql
ALTER TABLE emp_new
MODIFY last_name VARCHAR2(75);

4️⃣ Drop first_name column

sql
ALTER TABLE emp_new
DROP COLUMN first_name;

✔️ Check table description:

sql
DESC emp_new;

5️⃣ Add new column salary to emp_new

sql
ALTER TABLE emp_new
ADD salary NUMBER(10);

6️⃣ Rename dept_id column to deptno

sql
ALTER TABLE emp_new
RENAME COLUMN dept_id TO deptno;

7️⃣ Rename emp_new table to employee

sql
RENAME emp_new TO employee;

8️⃣ Create primary key on dept table (name: my_dept_id_pk)

sql
ALTER TABLE dept
ADD CONSTRAINT my_dept_id_pk PRIMARY KEY (dept_id);

9️⃣ Add foreign key in employee table

Constraint name: my_emp_dept_id_fk

sql
ALTER TABLE employee
ADD CONSTRAINT my_emp_dept_id_fk
FOREIGN KEY (deptno) 
REFERENCES dept(dept_id);

🔟 Modify last_name & first_name to NOT NULL

Since first_name was dropped earlier, we only update last_name.

sql
ALTER TABLE employee
MODIFY last_name VARCHAR2(75) NOT NULL;

1️⃣1️⃣ Confirm all constraints

sql
SELECT constraint_name, constraint_type, table_name
FROM user_constraints
WHERE table_name IN ('EMPLOYEE', 'DEPT');