SlideShare a Scribd company logo
Creation of Table 
Presented By 
Parteek Bhatia 
Assistant Professor 
Department of Computer Science & Engineering 
Thapar University, Patiala
What is Table? 
A table can represent a single entity (entity is an 
object whose information is stored in database) 
that you want to track within your system. Each 
entity or table has number of characteristics. The 
table must have a unique name through which it can 
be referred to after its creation .The 
characteristics of the table are called its 
attributes. These attributes can hold data.
What is Table? 
This type of a table could represent a list of the 
employees within your organization, or the orders placed 
for your company's products. A table has one attribute, 
which identifies each record uniquely; this attribute is 
called as Primary Key. Each value in the Primary Key 
attribute is unique and it cannot be NULL. Each record of 
the table is called as tuple. 
A table can also represent a relationship between two 
entities. This type of a table could portray the association 
between employees and their job skills, or the relationship 
of products to orders. Within the tables, foreign keys are 
used to represent relationships.
Table creation rules 
•Table name and Column name can be 1 to 30 characters 
long. First character must be alphabetic, but name may 
include letters, numbers and underscores. 
•Names must contain only the characters A-Z, a-z, 0-9, 
_(underscore),$ and # . 
•Names must not be an Oracle Server reserved word. 
•Names must not duplicate the names of other objects 
owned by the same Oracle server user. 
•Table name is not case sensitive.
SYNTAX 
• Create Table [schema] tablename 
( 
{Column datatype [DEFAULT expr] [column constraint], 
column datatype[DEFAULT expr] [column constraint],… 
[table_constraint]} 
); 
Create Table table_name( 
column_name datatype(width), 
column_name datatype(width),…….);
Schema 
It is the schema to contain the table. If it is omitted, 
Oracle creates the table in creator’s own schema. 
Table name 
It is the name of the table to be created. Table name 
and Column name can be 1 to 30 characters long. First 
character must be alphabetic, but name may include 
letters, numbers and underscores. The table name 
cannot be the name of another object owned by same 
user and cannot be a reserved word. 
Column 
Specifies the name of a column of the table. The number 
of columns in a table can range from 1 to 1000.
Datatype 
It is the datatype of a column. Specifies the type 
and width of data to be stored in the column. 
Default 
It specifies a value to be assigned to the column if 
a subsequent INSERT statement omits a value for 
the column. The datatype of the expression must 
match the datatype of the column. A DEFAULT 
expression cannot contain references to other 
columns, the pseudo columns CURRVAL, 
NEXTVAL, LEVEL and ROWNUM or data 
constants that are not fully specified.
SQL> Create table student 
(Name varchar2 (20), 
Class varchar2 (15), 
Roll_no number (4), 
Address varchar2 (30));
Role of Constraints to achieve data 
integrity 
To understand the role of constraints in database let us 
consider a case, when we appear for some interview, 
there are certain constraints for our qualification. 
Person who satisfies the given qualification constraints, 
only those person are eligible for interview, so these 
restrictions are called constraints which are to be 
enforced to select the correct candidate. Such 
limitations have to be enforced on the data to achieve 
the integrity (Correctness). The data, which does not, 
satisfies the conditions will not be stored, this ensures 
that the data stored in the database is valid and has 
gone through the integrity rules which prohibit the 
wrong data to be entered into the database.
Categories of Constraints 
There are two types of constraints, these are: 
• Column constraints 
• Table constraints. 
Column Constraints 
When we define constraints along the definition 
of the column while creating or altering the table 
structure, they are called as column constraints. Column 
constraints are applied only to the individual columns. 
These constraints are applied to the current column .A 
column level constraint cannot be applied if the data 
constraint spans across multiple columns in a table. 
For example: Empno of emp table is a primary key, which 
is column level constraint.
Table Level Constraints 
Table level constraints are applied to more than 
one column of a table. These constraints are 
applied after defining all the table columns when 
creating or altering the structure of the table. 
A table level constraint can be applied if the 
data constraint spans across multiple columns in 
a table.
Table Level Constraints 
• For example: In case of bank database the 
account number field of account holder table is 
not sufficient to uniquely identify the entities 
because two person can have joint account and 
hence repeating the value of account number 
once for each account holder, so in this case 
we have to apply primary key constraint on 
combination of account number field and name 
field to achieve the uniqueness. Now in this 
case the primary key constraint is applied on 
more than one column of the table so this is the 
table level constraint.
Types of Constraints 
NULL/NOT NULL 
Specifies if the column must contain value or might not contain any. 
By default all columns in a table allow nulls, i.e. absence of a value 
in a column. NOT NULL specifies that all rows in the table to have 
value for specified column. All NOT NULL columns are mandatory 
fields. Row of data will not be accepted for the table unless columns 
so defined have data in them. NULL columns might not contain any 
data and can be left empty. NULL should not be however specified 
for numeric fields as any arithmetic with NULL results in a NULL 
value. 
Syntax: 
Columnname datatype (size) [constraint 
constraintname] NOT NULL
Example 
• Create a table student with the fields name, roll_no, 
address and phone number. 
SQl> Create table student 
(Name varchar2 (20) CONSTRAINT NN_NAME NOT 
NULL, 
Roll_no number (5) NOT NULL, 
Address varchar2 (40), 
phone_no varchar2 (10));
Example 
SQL>CREATE TABLE sale( 
code char(4) NOT NULL, 
description VARCHAR2(15) CONSTRAINT desc_item NOT 
NULL, 
quantity NUMBER(5), sale_date DATE, notes CHAR(15) NULL); 
Above statement creates a table with fields code and description 
which is mandatory i.e. cannot be left empty and notes which is 
optional i.e. might not contain data.
Unique constraint 
The unique key allows unique values to be entered into 
the column i.e. every value is a distinct value in that 
column. When we apply a unique constraint on a group of 
columns then each value of the group should be unique, 
they must not be repeated. A table can have more than 
one unique key. This constraint can be applied both at 
the table level and the column level. The syntax is: 
Column level syntax: 
Columnname datatype (size) [constraint 
constraintname] UNIQUE
Unique constraint 
Example 
• Create a table student with roll_no not null, unique 
name, unique address and unique phone number. 
SQL> Create table student 
(Roll_no number (5) NOT NULL, 
name varchar2(20) contraint un_name unique, 
Address varchar2 (40) unique, 
phone_no varchar2 (10) unique); 
Table level syntax of unique constraint 
[Constraint constraintname] Unique (columnname [, 
columnname, …….])
Unique constraint 
• Create a table student with roll_no not 
null and the combination of name, address and 
phone number must be unique. 
SQL> Create table student 
(Roll_no number (5) NOT NULL, 
Name varchar2 (20), 
Address varchar2 (40), 
phone_no varchar2 (10), 
Constraint tb_un UNIQUE (name, address, 
phone_no));
Example 
SQL>CREATE TABLE item( 
code CHAR(4), description CHAR(10), rate NUMBER, 
UNIQUE (CODE, DESC)); 
The above statement creates a table item in which fields 
code and description cannot be duplicate or same for more 
than one record. In this example unique has been 
specified as table constraint.
Primary Key Constraint 
A primary key is used to identify each row of the table 
uniquely. A primary key may be either consists of a single 
field or group of fields. It is a combination of both the 
unique key constraint as well as the not null constraint i.e. 
no column with the primary key constraint can be left blank 
and it must contain unique value in each row. We can 
declare the Primary key of a table with NOT NULL and 
UNIQUE constraint .SQL supports primary keys directly 
with the Primary Key constraint. When primary key is 
applied on a single field it is called as Simple Key and when 
applied on multiple columns it is called as Composite 
Primary Key. In a table there is only one primary key.
Primary Key Constraint 
Column level syntax: 
Columnname datatype(size) [ constraint_name] 
PRIMARY KEY 
• Create a table student with roll_no as the Primary 
Key, unique name, address cannot be NULL and phone 
number. 
SQL> Create table student 
(Roll_no number (5) Primary key, 
Name varchar2 (20) Unique, 
Address varchar2 (40) Not Null, 
phone_no varchar2 (10));
Primary Key Constraint 
Table level syntax of Primary Key constraint 
PRIMARY KEY (columnname [, columnname , ……]) 
• Create a table student with name and class 
as the composite primary key, address and 
phone_no are the other fields. 
SQL> Create table student 
(Name varchar2 (20), 
Class varchar2 (15), 
Address varchar2 (40) Not Null, 
phone_no varchar2 (10) 
PRIMARY KEY (name, class));
Examples 
SQL>CREATE TABLE student ( 
name CHAR(10) PRIMARY KEY, class NUMBER, marks 
NUMBER); 
SQL>CREATE TABLE emp( 
empno NUMBER(4) PRIMARY KEY, 
ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), 
hiredate DATE, 
sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2));
Check Constraint 
Check constraints allow Oracle to verify the validity of 
data being entered on a table against a set of 
constants. These constants act as valid values. The 
Check constraint consists of the keyword CHECK 
followed by parenthesized conditions. Check constraints 
must be specified as a logical expression that evaluates 
either to TRUE or FALSE. If an SQL statement causes 
the condition to be false an error message will be 
displayed. 
Column level syntax: 
Columnname datatype (size) [constraint 
constraintname] CHECK (logical expression)
Check constraint 
• Create a table EMP1 with empid as primary 
key, phone number as unique attribute and the 
salary of all the employees must be greater than 
5000 with name and class as the composite 
primary key ,address and phone_no are the other 
fields. 
SQL> CREATE TABLE emp1 
(empid number (10) PRIMARY KEY, 
salary number (10, 3) CHECK (salary > 5000), 
home_phone number (12), 
CONSTRAINT uk_phone UNIQUE 
(home_phone));
If, for example, someone tries to create an employee 
row for the table defined earlier with a salary of Rs. 
1000, Oracle will return an error message saying that 
the record data defined for the SALARY column has 
violated the check constraint for that column.
Check constraint 
• Create a table emp1 with empid as primary 
key, phone number as unique attribute and the 
department of the employees must be either 
general or accounts, address and phone_no are 
the other fields. 
SQL> CREATE TABLE emp1 
(empid number (10) PRIMARY KEY, 
deptname varchar2 (20) CHECK 
(deptname in (‘general’,’accounts’)), 
home_phone number (12) UNIQUE);
Limitations of Check Constraints: 
Check constraints have a number of limitations, 
these are: 
• A column level check constraint cannot refer 
to another column of any table. 
• It cannot refer to special keywords that can 
have values in them, such as user, sysdate, or 
rowid.
• Example 1 
CREATE TABLE emp1 
(empid number (10), 
salary number (10, 3), 
Comm. number (10, 3), 
home_phone number (12), 
CONSTRAINT pk_empid 
PRIMARY KEY (empid), 
CONSTRAINT uk_phone UNIQUE (home_phone), 
CHECK (salary > comm));
• Example 2 
CREATE TABLE emp1 
(empid number (10), 
salary number (10, 3), 
Home_phone number (12), 
CONSTRAINT pk_empid 
PRIMARY KEY (empid), 
CONSTRAINT uk_phone UNIQUE (home_phone), 
CHECK (salary < 500000));
Example 
CREATE TABLE emp( 
code CHAR(4) PRIMARY KEY, name VARCHAR2(15) NOT 
NULL, 
department CHAR(10) CHECK (department IN 
(‘mkt’,’sales’,’Acct’)) 
age NUMBER CHECK (age between 18 and 55), 
basic NUMBER); 
Using in clause with a column the valid values to be entered in a 
column can be specified. Using between clauses the valid range can 
be specified.
Default constraint 
The default value constraint allows the user to 
insert the values in the columns where the user 
do not want to insert the value .The most 
common example of this constraint is NULL 
value, which is inserted in columns not defined 
with the NOT NULL constraint. This is not 
actually a constraint, it only specifies that a 
value should be inserted in a column if the user 
does not enter a value .The default values 
assignments are defined at the time of create 
table command. The datatype of the default 
value should match the datatype of the column.
The syntax is: 
Columnname datatype (size) DEFAULT value; 
SQL> Create table student 
(roll_no number(5) primary key, 
Name varchar2 (20) not null, 
Marks number (3) default 100, 
address varchar2 (30) not null));
Foreign Key constraint 
A foreign key is a kind of constraint, which 
establishes a relationship among tables. A 
foreign key may be a single column or the 
combinations of columns, which derive their 
values, based on the primary key or unique key 
values from another table. A foreign key 
constraint is also known as the referential 
integrity constraint, as its values correspond to 
the actual values of the primary key of other 
table.
A table in which there is a foreign key, it is 
called as the detail table or the child table and 
the table from which it refers the values of 
the primary key, it is called as the master table 
or the parent table .A foreign key must have 
the corresponding primary key or unique key 
value in the master table. Whenever you insert 
a value in the foreign key column, it checks the 
value from the primary key of the parent table. 
If the value is not present, it gives an error. 
The parent table can be referenced in the 
foreign key by using the references option.
Whenever a user tries to delete a record in 
the master table, which is being referenced in 
the child table, or the record exists in the 
child table, then the Oracle displays an error 
message. To avoid this error message, the ON 
DELETE CASCADE option is used which will 
delete the record in the detail table when the 
user deletes the record in the master table. 
The syntax of the foreign key at the column 
level is: 
Columnname datatype (size) references 
tablename [(columnname)] [ON DELETE 
CASCADE]
Examples 
Referenced table 
SQL>CREATE TABLE item( item_code CHAR(4) PRIMARY 
KEY, 
description VARCHAR(20, 
rate NUMBER(6,2)); 
Dependent table 
SQL>CREATE TABLE sales( 
invoice_no NUMBER(5), item_code CHAR(4) REFERENCES 
item(item_code), 
qty_sold NUMBER(5)); 
Item_code can be inserted in sales table only if it has references in 
item table i.e. it exists in the item table.
Referenced table 
SQL>CREATE TABLE dept (DEPTNO NUMBER(2) 
PRIMARY KEY, 
DNAME VARCHAR2(14), LOC VARCHAR2(13)) 
Dependent table 
SQL>CREATE TABLE emp( 
empno NUMBER(4) PRIMARY KEY, 
ename VARCHAR2(10), job VARCHAR2(9), mgr 
NUMBER(4), hiredate DATE, 
sal NUMBER(7,2), comm NUMBER(7,2), deptno 
NUMBER(2) REFERENCES dept(deptno) on delete 
set null);
SQL> Create table emp_detail 
(Empno number (4) primary key, 
Ename varchar2 (20) not null, 
Hiredate date not null, 
Deptno number (2), 
dname varchar2 (10), 
Salary number (6, 2) 
Foreign key (deptno,dname) references 
dept(deptno,dname)) ; 
So in this table deptno and dname is the foreign key, 
which references the corresponding fields in the dept 
table.
Other Options with foreign key
ON DELETE OPTION
ON DELETE OPTION
The user_constraints table 
A user can define multiple number of constraints 
in a table and if the user wishes to see the name 
of the constraints ,they are available in the 
USER_CONSTRINTS table .The DESCRIBE 
option only gives the name of the fields in the 
table and NOT NULL constraint associated with 
the column . So the user_constraints table 
provides information pertaining to the names of 
all the constraints on the table .The following 
fields is there in the user_constraints table:
Create table
So you can see the name of the constraints associated with 
the table by writing a simple SQL query. 
SQL>Select owner, constraint_name, r_owner, 
r_constraint_name from user_constraints where 
table_name = ‘EMP_DETAIL’; 
The Output is
SQL>Select * from user_constraints where 
table_name = ‘EMP’;
USER_CONS_COLUMNS 
• It can be used to see the list of constraints with 
the column name on a table. 
SELECT * FROM USER_CONS_COLUMNS;
Creating a Table with rows from another table 
A table is created using CREATE TABLE statement with 
rows in place, derived from another table. 
Syntax 
CREATE TABLE table_name 
[(Column name……………)] 
AS SELECT statement;
The table will be created with the specified columns and 
the rows retrieved by the SELECT statement inserted into 
it. If all the columns in the SELECT statement have well 
defined names, (that is, no expressions, and so on), the 
column specifications may be omitted. If column 
specifications are given, the number of columns must 
equal the number of items in the SELECT list. Constraints 
information is inherited from the selected table. Data type 
for the column cannot be specified.
Example 
• Create a table emp2 from emp table having employee number, 
name, mgr, and sal of employees in department 10 and 20. 
SQL>CREATE TABLE emp2 
AS 
SELECT empno, ename, mgr, sal FROM emp 
WHERE deptno in (10,20); 
Table created 
The above table contains all the records present in emp table having 
deptno 10 or deptno 20. Also the constraints attached to columns in 
emp table are attached to the columns of emp2 table.
• Create a table Salary from table emp having empno, 
ename and salary details. 
SQL> CREATE TABLE salary(employee_number,Name, 
Salary) 
AS 
SELECT empno, ename, sal FROM emp; 
Table created 
The above table contains records of table emp having 
empno, ename, salary details.
Creating table from an existing 
Table 
In addition to creating table as above, we can 
also create a new table from the existing table 
also .We apply the AS sub-query clause to both 
create the table and insert rows returned 
from the sub query. For example; 
SQL> Create table emp1 
AS 
Select empno, ename, hiredate, sal from EMP 
where comm IS NULL;
References 
Simplified Approach to Oracle 
Kalyani Publishers 
By 
Author Parteek Bhatia

More Related Content

What's hot (20)

PPTX
Triggers
Pooja Dixit
 
PPTX
trigger dbms
kuldeep100
 
PPTX
SQL(DDL & DML)
Sharad Dubey
 
PPTX
SQL commands
GirdharRatne
 
PPTX
SQL - DML and DDL Commands
Shrija Madhu
 
PDF
View & index in SQL
Swapnali Pawar
 
PPTX
Relational Data Model Introduction
Nishant Munjal
 
PPTX
SQL Joins.pptx
Ankit Rai
 
PDF
PL/SQL TRIGGERS
Lakshman Basnet
 
PPTX
Constructor in java
Pavith Gunasekara
 
PPT
Sql operators & functions 3
Dr. C.V. Suresh Babu
 
PPTX
DBMS Keys
Tarun Maheshwari
 
DOC
DBMS Practical File
Dushmanta Nath
 
PPT
Joins in SQL
Vigneshwaran Sankaran
 
PPT
14. Query Optimization in DBMS
koolkampus
 
PPTX
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
PPTX
joins in database
Sultan Arshad
 
PPTX
Introduction to database & sql
zahid6
 
PPTX
Sql clauses by Manan Pasricha
MananPasricha
 
Triggers
Pooja Dixit
 
trigger dbms
kuldeep100
 
SQL(DDL & DML)
Sharad Dubey
 
SQL commands
GirdharRatne
 
SQL - DML and DDL Commands
Shrija Madhu
 
View & index in SQL
Swapnali Pawar
 
Relational Data Model Introduction
Nishant Munjal
 
SQL Joins.pptx
Ankit Rai
 
PL/SQL TRIGGERS
Lakshman Basnet
 
Constructor in java
Pavith Gunasekara
 
Sql operators & functions 3
Dr. C.V. Suresh Babu
 
DBMS Keys
Tarun Maheshwari
 
DBMS Practical File
Dushmanta Nath
 
Joins in SQL
Vigneshwaran Sankaran
 
14. Query Optimization in DBMS
koolkampus
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
joins in database
Sultan Arshad
 
Introduction to database & sql
zahid6
 
Sql clauses by Manan Pasricha
MananPasricha
 

Similar to Create table (20)

PPT
Constraints In Sql
Anurag
 
PPT
Constraints constraints of oracle data base management systems
SHAKIR325211
 
PDF
RDBMS Lab03 applying constraints (UIU)
Muhammad T Q Nafis
 
PPTX
oracle Sql constraint
home
 
PPTX
data base programming chapter3 47 slides
nights1988
 
PPTX
apply Integrity constraints on database table
prachi gat
 
PPTX
Sql server ___________session_15(data integrity)
Ehtisham Ali
 
PPT
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
PPT
SQL Tutorial - Table Constraints
1keydata
 
PPT
Les09
Sudharsan S
 
PPTX
Constraints in Structure Query Language.
anjanasharma77573
 
PPTX
basic of SQL constraints in database management system
anjanasharma77573
 
PPTX
Data Definition Language Commands in DBMS
agrawalmonikacomp
 
PPT
Structure query language - Data definition language.ppt
munmunitjusl
 
PPTX
RELATIONALfsaaaaaaaaaaaakyagsgs MODEL.pptx
satish7588
 
PPTX
Database
NoorullahZamindar
 
ODP
BIS06 Physical Database Models
Prithwis Mukerjee
 
ODP
BIS06 Physical Database Models
Prithwis Mukerjee
 
PPTX
CONSTRAINTS PPT.pptx
ThangaduraiA4
 
PPT
Using ddl statements to create and manage tables
Syed Zaid Irshad
 
Constraints In Sql
Anurag
 
Constraints constraints of oracle data base management systems
SHAKIR325211
 
RDBMS Lab03 applying constraints (UIU)
Muhammad T Q Nafis
 
oracle Sql constraint
home
 
data base programming chapter3 47 slides
nights1988
 
apply Integrity constraints on database table
prachi gat
 
Sql server ___________session_15(data integrity)
Ehtisham Ali
 
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
SQL Tutorial - Table Constraints
1keydata
 
Constraints in Structure Query Language.
anjanasharma77573
 
basic of SQL constraints in database management system
anjanasharma77573
 
Data Definition Language Commands in DBMS
agrawalmonikacomp
 
Structure query language - Data definition language.ppt
munmunitjusl
 
RELATIONALfsaaaaaaaaaaaakyagsgs MODEL.pptx
satish7588
 
BIS06 Physical Database Models
Prithwis Mukerjee
 
BIS06 Physical Database Models
Prithwis Mukerjee
 
CONSTRAINTS PPT.pptx
ThangaduraiA4
 
Using ddl statements to create and manage tables
Syed Zaid Irshad
 
Ad

More from Nitesh Singh (20)

PPTX
Risk taking and emotions
Nitesh Singh
 
PDF
Project report RAILWAY TICKET RESERVATION SYSTEM SAD
Nitesh Singh
 
PPTX
The real comedy behind comedy
Nitesh Singh
 
PDF
Project report Rs Dry celaners
Nitesh Singh
 
PPTX
BIG DATA ANALYSIS
Nitesh Singh
 
DOCX
Udp vs-tcp
Nitesh Singh
 
PPT
Routing protocols-network-layer
Nitesh Singh
 
DOCX
Routers vs-switch
Nitesh Singh
 
PPT
New udp
Nitesh Singh
 
PPT
I pv4 format
Nitesh Singh
 
PPT
I pv4 addressing
Nitesh Singh
 
DOCX
Hub vs-switch
Nitesh Singh
 
PPTX
Ftp
Nitesh Singh
 
PPT
Email ftp
Nitesh Singh
 
PPTX
Www and http
Nitesh Singh
 
PDF
Transmission main
Nitesh Singh
 
PPT
Ta 104-topology
Nitesh Singh
 
PPT
Ta 104-topology (1)
Nitesh Singh
 
PPT
Ta 104-tcp
Nitesh Singh
 
PPT
Ta 104-media-3
Nitesh Singh
 
Risk taking and emotions
Nitesh Singh
 
Project report RAILWAY TICKET RESERVATION SYSTEM SAD
Nitesh Singh
 
The real comedy behind comedy
Nitesh Singh
 
Project report Rs Dry celaners
Nitesh Singh
 
BIG DATA ANALYSIS
Nitesh Singh
 
Udp vs-tcp
Nitesh Singh
 
Routing protocols-network-layer
Nitesh Singh
 
Routers vs-switch
Nitesh Singh
 
New udp
Nitesh Singh
 
I pv4 format
Nitesh Singh
 
I pv4 addressing
Nitesh Singh
 
Hub vs-switch
Nitesh Singh
 
Email ftp
Nitesh Singh
 
Www and http
Nitesh Singh
 
Transmission main
Nitesh Singh
 
Ta 104-topology
Nitesh Singh
 
Ta 104-topology (1)
Nitesh Singh
 
Ta 104-tcp
Nitesh Singh
 
Ta 104-media-3
Nitesh Singh
 
Ad

Recently uploaded (20)

PPTX
CST413 KTU S7 CSE Machine Learning Neural Networks and Support Vector Machine...
resming1
 
PDF
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
PDF
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
PPTX
Mobile database systems 20254545645.pptx
herosh1968
 
PPSX
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
PDF
CLIP_Internals_and_Architecture.pdf sdvsdv sdv
JoseLuisCahuanaRamos3
 
PDF
Rapid Prototyping for XR: Lecture 3 - Video and Paper Prototyping
Mark Billinghurst
 
PPT
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
PPTX
FSE_LLM4SE1_A Tool for In-depth Analysis of Code Execution Reasoning of Large...
cl144
 
PPTX
Computer network Computer network Computer network Computer network
Shrikant317689
 
PPTX
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
PDF
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
PPTX
CST413 KTU S7 CSE Machine Learning Introduction Parameter Estimation MLE MAP ...
resming1
 
PDF
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
PPTX
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
PPTX
Introduction to Python Programming Language
merlinjohnsy
 
PDF
01-introduction to the ProcessDesign.pdf
StiveBrack
 
PPTX
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
PPTX
Functions in Python Programming Language
BeulahS2
 
PDF
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 
CST413 KTU S7 CSE Machine Learning Neural Networks and Support Vector Machine...
resming1
 
FSE-Journal-First-Automated code editing with search-generate-modify.pdf
cl144
 
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
Mobile database systems 20254545645.pptx
herosh1968
 
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
CLIP_Internals_and_Architecture.pdf sdvsdv sdv
JoseLuisCahuanaRamos3
 
Rapid Prototyping for XR: Lecture 3 - Video and Paper Prototyping
Mark Billinghurst
 
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
FSE_LLM4SE1_A Tool for In-depth Analysis of Code Execution Reasoning of Large...
cl144
 
Computer network Computer network Computer network Computer network
Shrikant317689
 
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
CST413 KTU S7 CSE Machine Learning Introduction Parameter Estimation MLE MAP ...
resming1
 
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
Introduction to Python Programming Language
merlinjohnsy
 
01-introduction to the ProcessDesign.pdf
StiveBrack
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
Functions in Python Programming Language
BeulahS2
 
Decision support system in machine learning models for a face recognition-bas...
TELKOMNIKA JOURNAL
 

Create table

  • 1. Creation of Table Presented By Parteek Bhatia Assistant Professor Department of Computer Science & Engineering Thapar University, Patiala
  • 2. What is Table? A table can represent a single entity (entity is an object whose information is stored in database) that you want to track within your system. Each entity or table has number of characteristics. The table must have a unique name through which it can be referred to after its creation .The characteristics of the table are called its attributes. These attributes can hold data.
  • 3. What is Table? This type of a table could represent a list of the employees within your organization, or the orders placed for your company's products. A table has one attribute, which identifies each record uniquely; this attribute is called as Primary Key. Each value in the Primary Key attribute is unique and it cannot be NULL. Each record of the table is called as tuple. A table can also represent a relationship between two entities. This type of a table could portray the association between employees and their job skills, or the relationship of products to orders. Within the tables, foreign keys are used to represent relationships.
  • 4. Table creation rules •Table name and Column name can be 1 to 30 characters long. First character must be alphabetic, but name may include letters, numbers and underscores. •Names must contain only the characters A-Z, a-z, 0-9, _(underscore),$ and # . •Names must not be an Oracle Server reserved word. •Names must not duplicate the names of other objects owned by the same Oracle server user. •Table name is not case sensitive.
  • 5. SYNTAX • Create Table [schema] tablename ( {Column datatype [DEFAULT expr] [column constraint], column datatype[DEFAULT expr] [column constraint],… [table_constraint]} ); Create Table table_name( column_name datatype(width), column_name datatype(width),…….);
  • 6. Schema It is the schema to contain the table. If it is omitted, Oracle creates the table in creator’s own schema. Table name It is the name of the table to be created. Table name and Column name can be 1 to 30 characters long. First character must be alphabetic, but name may include letters, numbers and underscores. The table name cannot be the name of another object owned by same user and cannot be a reserved word. Column Specifies the name of a column of the table. The number of columns in a table can range from 1 to 1000.
  • 7. Datatype It is the datatype of a column. Specifies the type and width of data to be stored in the column. Default It specifies a value to be assigned to the column if a subsequent INSERT statement omits a value for the column. The datatype of the expression must match the datatype of the column. A DEFAULT expression cannot contain references to other columns, the pseudo columns CURRVAL, NEXTVAL, LEVEL and ROWNUM or data constants that are not fully specified.
  • 8. SQL> Create table student (Name varchar2 (20), Class varchar2 (15), Roll_no number (4), Address varchar2 (30));
  • 9. Role of Constraints to achieve data integrity To understand the role of constraints in database let us consider a case, when we appear for some interview, there are certain constraints for our qualification. Person who satisfies the given qualification constraints, only those person are eligible for interview, so these restrictions are called constraints which are to be enforced to select the correct candidate. Such limitations have to be enforced on the data to achieve the integrity (Correctness). The data, which does not, satisfies the conditions will not be stored, this ensures that the data stored in the database is valid and has gone through the integrity rules which prohibit the wrong data to be entered into the database.
  • 10. Categories of Constraints There are two types of constraints, these are: • Column constraints • Table constraints. Column Constraints When we define constraints along the definition of the column while creating or altering the table structure, they are called as column constraints. Column constraints are applied only to the individual columns. These constraints are applied to the current column .A column level constraint cannot be applied if the data constraint spans across multiple columns in a table. For example: Empno of emp table is a primary key, which is column level constraint.
  • 11. Table Level Constraints Table level constraints are applied to more than one column of a table. These constraints are applied after defining all the table columns when creating or altering the structure of the table. A table level constraint can be applied if the data constraint spans across multiple columns in a table.
  • 12. Table Level Constraints • For example: In case of bank database the account number field of account holder table is not sufficient to uniquely identify the entities because two person can have joint account and hence repeating the value of account number once for each account holder, so in this case we have to apply primary key constraint on combination of account number field and name field to achieve the uniqueness. Now in this case the primary key constraint is applied on more than one column of the table so this is the table level constraint.
  • 13. Types of Constraints NULL/NOT NULL Specifies if the column must contain value or might not contain any. By default all columns in a table allow nulls, i.e. absence of a value in a column. NOT NULL specifies that all rows in the table to have value for specified column. All NOT NULL columns are mandatory fields. Row of data will not be accepted for the table unless columns so defined have data in them. NULL columns might not contain any data and can be left empty. NULL should not be however specified for numeric fields as any arithmetic with NULL results in a NULL value. Syntax: Columnname datatype (size) [constraint constraintname] NOT NULL
  • 14. Example • Create a table student with the fields name, roll_no, address and phone number. SQl> Create table student (Name varchar2 (20) CONSTRAINT NN_NAME NOT NULL, Roll_no number (5) NOT NULL, Address varchar2 (40), phone_no varchar2 (10));
  • 15. Example SQL>CREATE TABLE sale( code char(4) NOT NULL, description VARCHAR2(15) CONSTRAINT desc_item NOT NULL, quantity NUMBER(5), sale_date DATE, notes CHAR(15) NULL); Above statement creates a table with fields code and description which is mandatory i.e. cannot be left empty and notes which is optional i.e. might not contain data.
  • 16. Unique constraint The unique key allows unique values to be entered into the column i.e. every value is a distinct value in that column. When we apply a unique constraint on a group of columns then each value of the group should be unique, they must not be repeated. A table can have more than one unique key. This constraint can be applied both at the table level and the column level. The syntax is: Column level syntax: Columnname datatype (size) [constraint constraintname] UNIQUE
  • 17. Unique constraint Example • Create a table student with roll_no not null, unique name, unique address and unique phone number. SQL> Create table student (Roll_no number (5) NOT NULL, name varchar2(20) contraint un_name unique, Address varchar2 (40) unique, phone_no varchar2 (10) unique); Table level syntax of unique constraint [Constraint constraintname] Unique (columnname [, columnname, …….])
  • 18. Unique constraint • Create a table student with roll_no not null and the combination of name, address and phone number must be unique. SQL> Create table student (Roll_no number (5) NOT NULL, Name varchar2 (20), Address varchar2 (40), phone_no varchar2 (10), Constraint tb_un UNIQUE (name, address, phone_no));
  • 19. Example SQL>CREATE TABLE item( code CHAR(4), description CHAR(10), rate NUMBER, UNIQUE (CODE, DESC)); The above statement creates a table item in which fields code and description cannot be duplicate or same for more than one record. In this example unique has been specified as table constraint.
  • 20. Primary Key Constraint A primary key is used to identify each row of the table uniquely. A primary key may be either consists of a single field or group of fields. It is a combination of both the unique key constraint as well as the not null constraint i.e. no column with the primary key constraint can be left blank and it must contain unique value in each row. We can declare the Primary key of a table with NOT NULL and UNIQUE constraint .SQL supports primary keys directly with the Primary Key constraint. When primary key is applied on a single field it is called as Simple Key and when applied on multiple columns it is called as Composite Primary Key. In a table there is only one primary key.
  • 21. Primary Key Constraint Column level syntax: Columnname datatype(size) [ constraint_name] PRIMARY KEY • Create a table student with roll_no as the Primary Key, unique name, address cannot be NULL and phone number. SQL> Create table student (Roll_no number (5) Primary key, Name varchar2 (20) Unique, Address varchar2 (40) Not Null, phone_no varchar2 (10));
  • 22. Primary Key Constraint Table level syntax of Primary Key constraint PRIMARY KEY (columnname [, columnname , ……]) • Create a table student with name and class as the composite primary key, address and phone_no are the other fields. SQL> Create table student (Name varchar2 (20), Class varchar2 (15), Address varchar2 (40) Not Null, phone_no varchar2 (10) PRIMARY KEY (name, class));
  • 23. Examples SQL>CREATE TABLE student ( name CHAR(10) PRIMARY KEY, class NUMBER, marks NUMBER); SQL>CREATE TABLE emp( empno NUMBER(4) PRIMARY KEY, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2));
  • 24. Check Constraint Check constraints allow Oracle to verify the validity of data being entered on a table against a set of constants. These constants act as valid values. The Check constraint consists of the keyword CHECK followed by parenthesized conditions. Check constraints must be specified as a logical expression that evaluates either to TRUE or FALSE. If an SQL statement causes the condition to be false an error message will be displayed. Column level syntax: Columnname datatype (size) [constraint constraintname] CHECK (logical expression)
  • 25. Check constraint • Create a table EMP1 with empid as primary key, phone number as unique attribute and the salary of all the employees must be greater than 5000 with name and class as the composite primary key ,address and phone_no are the other fields. SQL> CREATE TABLE emp1 (empid number (10) PRIMARY KEY, salary number (10, 3) CHECK (salary > 5000), home_phone number (12), CONSTRAINT uk_phone UNIQUE (home_phone));
  • 26. If, for example, someone tries to create an employee row for the table defined earlier with a salary of Rs. 1000, Oracle will return an error message saying that the record data defined for the SALARY column has violated the check constraint for that column.
  • 27. Check constraint • Create a table emp1 with empid as primary key, phone number as unique attribute and the department of the employees must be either general or accounts, address and phone_no are the other fields. SQL> CREATE TABLE emp1 (empid number (10) PRIMARY KEY, deptname varchar2 (20) CHECK (deptname in (‘general’,’accounts’)), home_phone number (12) UNIQUE);
  • 28. Limitations of Check Constraints: Check constraints have a number of limitations, these are: • A column level check constraint cannot refer to another column of any table. • It cannot refer to special keywords that can have values in them, such as user, sysdate, or rowid.
  • 29. • Example 1 CREATE TABLE emp1 (empid number (10), salary number (10, 3), Comm. number (10, 3), home_phone number (12), CONSTRAINT pk_empid PRIMARY KEY (empid), CONSTRAINT uk_phone UNIQUE (home_phone), CHECK (salary > comm));
  • 30. • Example 2 CREATE TABLE emp1 (empid number (10), salary number (10, 3), Home_phone number (12), CONSTRAINT pk_empid PRIMARY KEY (empid), CONSTRAINT uk_phone UNIQUE (home_phone), CHECK (salary < 500000));
  • 31. Example CREATE TABLE emp( code CHAR(4) PRIMARY KEY, name VARCHAR2(15) NOT NULL, department CHAR(10) CHECK (department IN (‘mkt’,’sales’,’Acct’)) age NUMBER CHECK (age between 18 and 55), basic NUMBER); Using in clause with a column the valid values to be entered in a column can be specified. Using between clauses the valid range can be specified.
  • 32. Default constraint The default value constraint allows the user to insert the values in the columns where the user do not want to insert the value .The most common example of this constraint is NULL value, which is inserted in columns not defined with the NOT NULL constraint. This is not actually a constraint, it only specifies that a value should be inserted in a column if the user does not enter a value .The default values assignments are defined at the time of create table command. The datatype of the default value should match the datatype of the column.
  • 33. The syntax is: Columnname datatype (size) DEFAULT value; SQL> Create table student (roll_no number(5) primary key, Name varchar2 (20) not null, Marks number (3) default 100, address varchar2 (30) not null));
  • 34. Foreign Key constraint A foreign key is a kind of constraint, which establishes a relationship among tables. A foreign key may be a single column or the combinations of columns, which derive their values, based on the primary key or unique key values from another table. A foreign key constraint is also known as the referential integrity constraint, as its values correspond to the actual values of the primary key of other table.
  • 35. A table in which there is a foreign key, it is called as the detail table or the child table and the table from which it refers the values of the primary key, it is called as the master table or the parent table .A foreign key must have the corresponding primary key or unique key value in the master table. Whenever you insert a value in the foreign key column, it checks the value from the primary key of the parent table. If the value is not present, it gives an error. The parent table can be referenced in the foreign key by using the references option.
  • 36. Whenever a user tries to delete a record in the master table, which is being referenced in the child table, or the record exists in the child table, then the Oracle displays an error message. To avoid this error message, the ON DELETE CASCADE option is used which will delete the record in the detail table when the user deletes the record in the master table. The syntax of the foreign key at the column level is: Columnname datatype (size) references tablename [(columnname)] [ON DELETE CASCADE]
  • 37. Examples Referenced table SQL>CREATE TABLE item( item_code CHAR(4) PRIMARY KEY, description VARCHAR(20, rate NUMBER(6,2)); Dependent table SQL>CREATE TABLE sales( invoice_no NUMBER(5), item_code CHAR(4) REFERENCES item(item_code), qty_sold NUMBER(5)); Item_code can be inserted in sales table only if it has references in item table i.e. it exists in the item table.
  • 38. Referenced table SQL>CREATE TABLE dept (DEPTNO NUMBER(2) PRIMARY KEY, DNAME VARCHAR2(14), LOC VARCHAR2(13)) Dependent table SQL>CREATE TABLE emp( empno NUMBER(4) PRIMARY KEY, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2) REFERENCES dept(deptno) on delete set null);
  • 39. SQL> Create table emp_detail (Empno number (4) primary key, Ename varchar2 (20) not null, Hiredate date not null, Deptno number (2), dname varchar2 (10), Salary number (6, 2) Foreign key (deptno,dname) references dept(deptno,dname)) ; So in this table deptno and dname is the foreign key, which references the corresponding fields in the dept table.
  • 40. Other Options with foreign key
  • 43. The user_constraints table A user can define multiple number of constraints in a table and if the user wishes to see the name of the constraints ,they are available in the USER_CONSTRINTS table .The DESCRIBE option only gives the name of the fields in the table and NOT NULL constraint associated with the column . So the user_constraints table provides information pertaining to the names of all the constraints on the table .The following fields is there in the user_constraints table:
  • 45. So you can see the name of the constraints associated with the table by writing a simple SQL query. SQL>Select owner, constraint_name, r_owner, r_constraint_name from user_constraints where table_name = ‘EMP_DETAIL’; The Output is
  • 46. SQL>Select * from user_constraints where table_name = ‘EMP’;
  • 47. USER_CONS_COLUMNS • It can be used to see the list of constraints with the column name on a table. SELECT * FROM USER_CONS_COLUMNS;
  • 48. Creating a Table with rows from another table A table is created using CREATE TABLE statement with rows in place, derived from another table. Syntax CREATE TABLE table_name [(Column name……………)] AS SELECT statement;
  • 49. The table will be created with the specified columns and the rows retrieved by the SELECT statement inserted into it. If all the columns in the SELECT statement have well defined names, (that is, no expressions, and so on), the column specifications may be omitted. If column specifications are given, the number of columns must equal the number of items in the SELECT list. Constraints information is inherited from the selected table. Data type for the column cannot be specified.
  • 50. Example • Create a table emp2 from emp table having employee number, name, mgr, and sal of employees in department 10 and 20. SQL>CREATE TABLE emp2 AS SELECT empno, ename, mgr, sal FROM emp WHERE deptno in (10,20); Table created The above table contains all the records present in emp table having deptno 10 or deptno 20. Also the constraints attached to columns in emp table are attached to the columns of emp2 table.
  • 51. • Create a table Salary from table emp having empno, ename and salary details. SQL> CREATE TABLE salary(employee_number,Name, Salary) AS SELECT empno, ename, sal FROM emp; Table created The above table contains records of table emp having empno, ename, salary details.
  • 52. Creating table from an existing Table In addition to creating table as above, we can also create a new table from the existing table also .We apply the AS sub-query clause to both create the table and insert rows returned from the sub query. For example; SQL> Create table emp1 AS Select empno, ename, hiredate, sal from EMP where comm IS NULL;
  • 53. References Simplified Approach to Oracle Kalyani Publishers By Author Parteek Bhatia