Presentation is loading. Please wait.

Presentation is loading. Please wait.

Using DDL Statements to Create and Manage Tables Lecture 3 Md. Ariful Islam Khandaker Assistant Professor, IICT Khulna University of Engineering & Technology.

Similar presentations


Presentation on theme: "Using DDL Statements to Create and Manage Tables Lecture 3 Md. Ariful Islam Khandaker Assistant Professor, IICT Khulna University of Engineering & Technology."— Presentation transcript:

1 Using DDL Statements to Create and Manage Tables Lecture 3 Md. Ariful Islam Khandaker Assistant Professor, IICT Khulna University of Engineering & Technology (KUET)

2 Spot Test Time: 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 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 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.

3 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

4 Database Objects Logically represents subsets of data from one or more tables View Generates numeric valuesSequence Basic unit of storage; composed of rowsTable Gives alternative name to an objectSynonym Improves the performance of some queriesIndex DescriptionObject

5 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

6 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][,...]);

7 Referencing Another Users Tables Tables belonging to other users are not in the users schema. You should use the owners name as a prefix to those tables. USERBUSERA SELECT * FROM userB.employees; SELECT * FROM userA.employees;

8 DEFAULT Option Specify a default value for a column during an insert. Literal values, expressions, or SQL functions are legal values. Another columns 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);

9 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

10 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);

11 Data Types Raw binary data RAW 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 values DATE 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 data CHAR(size) Variable-length numeric data NUMBER(p,s) Variable-length character data VARCHAR2(size) DescriptionData Type

12 Datetime Data Types You can use several datetime data types: Stored as an interval of years and months INTERVAL YEAR TO MONTH Stored as an interval of days, hours, minutes, and seconds INTERVAL DAY TO SECOND Date with fractional seconds TIMESTAMP DescriptionData Type

13 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

14 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.

15 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,

16 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

17 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 …

18 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) )

19 UNIQUE Constraint EMPLOYEES UNIQUE constraint INSERT INTO Not allowed: already exists Allowed …

20 UNIQUE Constraint Defined at either the table level or the column level: CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL,... CONSTRAINT emp_ _uk UNIQUE( )); 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) )

21 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 Persons ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName) To DROP a UNIQUE Constraint To drop a UNIQUE constraint, use the following SQL: ALTER TABLE Persons DROP CONSTRAINT uc_PersonID

22 PRIMARY KEY Constraint DEPARTMENTS PRIMARY KEY INSERT INTO Not allowed (null value) Not allowed (50 already exists)

23 PRIMARY KEY Constraint Continue The 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) )

24 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 Persons ADD 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 Persons DROP CONSTRAINT pk_PersonID

25 FOREIGN KEY Constraint DEPARTMENTS EMPLOYEES FOREIGN KEY INSERT INTO Not allowed (9 does not exist) Allowed PRIMARY KEY … …

26 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, 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_ _uk UNIQUE( ));

27 FOREIGN KEY Constraint Example P_IdLastNameFirstNameAddressCity 1HansenOlaTimoteivn 10 Sandnes 2SvendsonToveBorgvn 23Sandnes 3PettersenKariStorgt 20Stavanger O_IdOrderNoP_Id 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.

28 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

29 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

30 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..., salaryNUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),...

31 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') )

32 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

33 CREATE TABLE : Example CREATE 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, VARCHAR2(25) CONSTRAINT emp_ _nn NOT NULL CONSTRAINT emp_ _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));

34 UPDATE employees SET department_id = 55 WHERE department_id = 110; Violating Constraints Department 55 does not exist.

35 Violating Constraints You cannot delete a row that contains a primary key that is used as a foreign key in another table. DELETE FROM departments WHERE department_id = 60;

36 Creating a Table Using 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;

37 CREATE TABLE dept80 AS SELECT employee_id, last_name, salary*12 ANNSAL, hire_date FROM employees WHERE department_id = 80; Creating a Table Using a Subquery DESCRIBE dept80

38 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

39 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

40 ALTER TABLE Statement Example Look at the "Persons" table: P_IdLastNameFirstNameAddressCity 1HansenOlaTimoteivn 10 Sandnes 2SvendsonToveBorgvn 23Sandnes 3PettersenKariStorgt 20Stavanger 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_IdLastNam e FirstNam e AddressCityDateOfBi rth 1HansenOlaTimoteiv n 10 Sandnes 2Svendso n ToveBorgvn 23 Sandnes

41 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;

42 AUTO INCREMENT a Field Very 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')

43 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_person MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 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')

44 Dropping a Table Moves a table to the recycle bin Invalidates dependent objects and removes object privileges on the table DROP TABLE dept80;

45 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


Download ppt "Using DDL Statements to Create and Manage Tables Lecture 3 Md. Ariful Islam Khandaker Assistant Professor, IICT Khulna University of Engineering & Technology."

Similar presentations


Ads by Google