Using DDL Statementsto Create and Manage Tables
Lecture 3
Md. Ariful Islam Khandaker
Assistant Professor, IICT
Khulna University of Engineering & Technology (KUET)
Spot TestTime: 15 min Mark: 10
1. Display all employee last names in which the third letter of the name is “a”.
2. Display the last name and salary for any employee whose salary is not in the range 5000 to 12000.
3. Create a report to display the last name, job ID, and hire date for employees with the last name of Matos and Taylor. Order the query in ascending order by hire date.
4. Display the last name and salary of employees who earn between 6000 and 12000 are in department 20, 30 or 50. Label the columns are Employee and Monthly salary.
5. Create a report to display the last name and job title of all employees who do not have a manager.
Objectives
After completing this lesson, you should be able to do the following:
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
• Create a simple table
• Explain how constraints are created at the time of table creation
• Describe how schema objects work
Database Objects
Logically represents subsets of data from one or more tables
View
Generates numeric valuesSequence
Basic unit of storage; composed of rows Table
Gives alternative name to an objectSynonym
Improves the performance of some queriesIndex
DescriptionObject
Naming Rules
Table names and column names:
• Must begin with a letter
• Must be 1–30 characters long
• Must contain only A–Z, a–z, 0–9, _, $, and #
• Must not duplicate the name of another object owned by the same user
• Must not be an Oracle server–reserved word
CREATE TABLE Statement
• You must have:– CREATE TABLE privilege– A storage area
• You specify:– Table name– Column name, column data type, and column size
CREATE TABLE [schema.]table (column datatype [DEFAULT expr][, ...]);
Referencing Another User’s Tables
• Tables belonging to other users are not in the user’s schema.
• You should use the owner’s name as a prefix to those tables.
USERBUSERA
SELECT * FROM userB.employees;
SELECT * FROM userA.employees;
DEFAULT Option
• Specify a default value for a column during an insert.
• Literal values, expressions, or SQL functions are legal values.
• Another column’s name or a pseudocolumn are illegal values.
• The default data type must match the column data type.
... hire_date DATE DEFAULT SYSDATE, ...
CREATE TABLE hire_dates (id NUMBER(8), hire_date DATE DEFAULT SYSDATE);
SQL DEFAULT Constraint on ALTER TABLE
To create a DEFAULT constraint on the "City" column when the table is already created, use the following SQL:
MySql: ALTER TABLE Persons ALTER City SET DEFAULT 'SANDNES'
Oracle: ALTER TABLE Persons MODIFY City DEFAULT 'SANDNES'
Access: ALTER TABLE Persons ALTER COLUMN City SET DEFAULT 'SANDNES'
DROP a DEFAULT Constraint
MySql: ALTER TABLE Persons ALTER City DROP DEFAULT
Oracle/ Access: ALTER TABLE Persons ALTER COLUMN City DROP DEFAULT
Creating Tables
• Create the table:
• Confirm table creation:
DESCRIBE dept
CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13), create_date DATE DEFAULT SYSDATE);
Data Types
Raw binary dataRAW and LONG RAW
Binary data (up to 4 GB)BLOB
Binary data stored in an external file (up to 4 GB)BFILE
Date and time valuesDATE
Variable-length character data (up to 2 GB)LONG
Character data (up to 4 GB)CLOB
A base-64 number system representing the unique address of a row in its table
ROWID
Fixed-length character dataCHAR(size)
Variable-length numeric dataNUMBER(p,s)
Variable-length character dataVARCHAR2(size)
DescriptionData Type
Datetime Data Types
You can use several datetime data types:
Stored as an interval of yearsand months
INTERVAL YEAR TO MONTH
Stored as an interval of days, hours, minutes, and seconds
INTERVAL DAY TO SECOND
Date with fractional secondsTIMESTAMP
DescriptionData Type
Including Constraints
• Constraints enforce rules at the table level.
• Constraints prevent the deletion of a table if there are dependencies.
• The following constraint types are valid:– NOT NULL– UNIQUE– PRIMARY KEY– FOREIGN KEY– CHECK
Constraint Guidelines
• You can name a constraint, or the Oracle server generates a name by using the SYS_Cn format.
• Create a constraint at either of the following times:– At the same time as the creation of the table– After the creation of the table
• Define a constraint at the column or table level.
• View a constraint in the data dictionary.
Defining Constraints
• Syntax:
• Column-level constraint syntax:
• Table-level constraint syntax:
CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint][,...]);
column,... [CONSTRAINT constraint_name] constraint_type (column, ...),
column [CONSTRAINT constraint_name] constraint_type,
Defining Constraints
• Example of a column-level constraint:
• Example of a table-level constraint:
CREATE TABLE employees( employee_id NUMBER(6) CONSTRAINT emp_emp_id_pk PRIMARY KEY, first_name VARCHAR2(20), ...);
CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), ... job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID));
1
2
NOT NULL Constraint
Ensures that null values are not permitted for the column:
NOT NULL constraint(Primary Key enforces NOT NULL constraint.)
Absence of NOT NULL constraint (Any row can contain a null value for this column.)
NOT NULL constraint
…
NOT NULL Constraint Example
1. The NOT NULL constraint enforces a column to NOT accept NULL values.
2. The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values:
CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))
UNIQUE Constraint
EMPLOYEES UNIQUE constraint
INSERT INTO
Not allowed: already exists
Allowed
…
UNIQUE ConstraintDefined at either the table level or the column level:
CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL,... CONSTRAINT emp_email_uk UNIQUE(email));
CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id, LastName))
UNIQUE Constraint Continue…
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the following SQL:
1. ALTER TABLE Persons ADD UNIQUE (P_Id)
2. ALTER TABLE PersonsADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
To DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL:
ALTER TABLE PersonsDROP CONSTRAINT uc_PersonID
PRIMARY KEY Constraint
DEPARTMENTS PRIMARY KEY
INSERT INTONot allowed(null value)
Not allowed (50 already exists)
PRIMARY KEY Constraint ContinueThe PRIMARY KEY constraint uniquely identifies each record in a database table.Primary keys must contain unique values.A primary key column cannot contain NULL values.Each table should have a primary key, and each table can have only ONE primary key.
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
PRIMARY KEY Constraint Continue SQL PRIMARY KEY Constraint on ALTER TABLE
To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the following SQL:
1. ALTER TABLE Persons ADD PRIMARY KEY (P_Id)
2. ALTER TABLE PersonsADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
1. ALTER TABLE Persons DROP PRIMARY KEY
2. ALTER TABLE PersonsDROP CONSTRAINT pk_PersonID
FOREIGN KEY Constraint
DEPARTMENTS
EMPLOYEESFOREIGNKEY
INSERT INTO Not allowed(9 does not
exist)Allowed
PRIMARYKEY
…
…
FOREIGN KEY Constraint
Defined at either the table level or the column level:
CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL,... department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments(department_id), CONSTRAINT emp_email_uk UNIQUE(email));
FOREIGN KEY Constraint Example
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10
Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Let's illustrate the foreign key with an example. Look at the following two tables: "Persons" table and "Orders" table
The "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
SQL FOREIGN KEY Constraint on CREATE TABLE The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:
CREATE TABLE Orders(O_Id int NOT NULL PRIMARY KEY,OrderNo int NOT NULL,P_Id int FOREIGN KEY REFERENCES Persons(P_Id))
SQL FOREIGN KEY Constraint on ALTER TABLE
ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
or
ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)REFERENCES Persons(P_Id)
To DROP a FOREIGN KEY Constraint
In MySql: ALTER TABLE OrdersDROP FOREIGN KEY fk_PerOrders
In Oracle/ Access: ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders
FOREIGN KEY Constraint:Keywords
• FOREIGN KEY: Defines the column in the child table at the table-constraint level
• REFERENCES: Identifies the table and column in the parent table
• ON DELETE CASCADE: Deletes the dependent rows in the child table when a row in the parent table is deleted
• ON DELETE SET NULL: Converts dependent foreign key values to null
CHECK Constraint
• Defines a condition that each row must satisfy
• The following expressions are not allowed:– References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM
pseudocolumns– Calls to SYSDATE, UID, USER, and USERENV functions– Queries that refer to other values in other rows
..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),...
CHECK Constraint Continue…The CHECK constraint is used to limit the value range that can be placed in a column.If you define a CHECK constraint on a single column it allows only certain values for this column.CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255), CHECK (P_Id>0))
CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes'))
CHECK Constraint Continue…
SQL CHECK Constraint on ALTER TABLE
To create a CHECK constraint on the "P_Id" column when the table is already created, use the following SQL:
ALTER TABLE Persons ADD CHECK (P_Id>0)
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:
ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
To DROP a CHECK Constraint
In oracle/Access: ALTER TABLE Persons DROP CONSTRAINT chk_Person
In MySql: ALTER TABLE Persons DROP CHECK chk_Person
CREATE TABLE: ExampleCREATE TABLE employees ( employee_id NUMBER(6) CONSTRAINT emp_employee_id PRIMARY KEY , first_name VARCHAR2(20) , last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn NOT NULL , email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL CONSTRAINT emp_email_uk UNIQUE , phone_number VARCHAR2(20) , hire_date DATE CONSTRAINT emp_hire_date_nn NOT NULL , job_id VARCHAR2(10) CONSTRAINT emp_job_nn NOT NULL , salary NUMBER(8,2) CONSTRAINT emp_salary_ck CHECK (salary>0) , commission_pct NUMBER(2,2) , manager_id NUMBER(6)
CONSTRAINT emp_manager_fk REFERENCES employees (employee_id)
, department_id NUMBER(4) CONSTRAINT emp_dept_fk REFERENCES departments (department_id));
UPDATE employeesSET department_id = 55WHERE department_id = 110;
Violating Constraints
Department 55 does not exist.
Violating Constraints
You cannot delete a row that contains a primary key that is used as a foreign key in another table.
DELETE FROM departmentsWHERE department_id = 60;
Creating a TableUsing a Subquery
• Create a table and insert rows by combining the CREATE TABLE statement and the AS subquery option.
• Match the number of specified columns to the number of subquery columns.
• Define columns with column names and default values.
CREATE TABLE table [(column, column...)]AS subquery;
CREATE TABLE dept80 AS SELECT employee_id, last_name, salary*12 ANNSAL, hire_date FROM employees WHERE department_id = 80;
Creating a TableUsing a Subquery
DESCRIBE dept80
ALTER TABLE Statement
Use the ALTER TABLE statement to:
• Add a new column
• Modify an existing column definition
• Define a default value for the new column
• Drop a column
• Rename a column
• Change table to read-only status
ALTER TABLE Statement Continue…
To add a column in a table, use the following syntax:
Structure: ALTER TABLE table_name ADD column_name datatype
To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):
Structure: ALTER TABLE table_name DROP COLUMN column_name
To change the data type of a column in a table, use the following syntax:
Structure: ALTER TABLE table_name MODIFY column_name datatype
ALTER TABLE Statement Example Look at the "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10
Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to add a column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
ALTER TABLE Persons ADD DateOfBirth date
P_Id LastName
FirstName
Address City DateOfBirth
1 Hansen Ola Timoteivn 10
Sandnes
2 Svendson
Tove Borgvn 23
Sandnes
Read-Only Tables
Use the ALTER TABLE syntax to put a table into the read-only mode:
• Prevents DDL or DML changes during table maintenance
• Change it back into read/write mode
ALTER TABLE employees READ ONLY;
-- perform table maintenance and then-- return table back to read/write mode
ALTER TABLE employees READ WRITE;
AUTO INCREMENT a FieldVery often we would like the value of the primary key field to be created automatically every time a new record is inserted.We would like to create an auto-increment field in a table.
Syntax for MySQL
The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table:
CREATE TABLE Persons(P_Id int NOT NULL AUTO_INCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255), PRIMARY KEY (P_Id))
To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)VALUES ('Lars','Monsen')
AUTO INCREMENT a Field Continue…
Syntax for Oracle
In Oracle the code is a little bit more tricky.You will have to create an auto-increment field with the sequence object (this object generates a number sequence).Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_personMINVALUE 1START WITH 1INCREMENT BY 1CACHE 10
The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.
INSERT INTO Persons (P_Id, FirstName, LastName) VALUES (seq_person.nextval, 'Lars', 'Monsen')
Dropping a Table
• Moves a table to the recycle bin
• Invalidates dependent objects and removes object privileges on the table
DROP TABLE dept80;
Summary
In this lesson, you should have learned how to use the CREATE TABLE statement to create a table and include constraints:
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
• Create a simple table
• Explain how constraints are created at the time of table creation
• Describe how schema objects work
Top Related