SlideShare a Scribd company logo
1Using ORACLE®Data Definition Language(Creating our sample database)  Indexes and Views
2DATA DEFINATION LANGUAGEData Definition language abbreviated as DDL refers to the set of commands used to define the data containers in Oracle like Tables and also defining Views and Indexes.Basically there are 3 DDL commands viz:
3THE CREATE COMMANDThe “CREATE” command can be used to create a table, view, index etc.Let us look at creating a table:In order to create a table a user must have the privileges to create tables i.e.			The “CREATE TABLE” privilege.The basic syntax to create a table is :CREATE TABLE [schema.]TABLENAME			            ( colm1_name datatype[size] [colm_level_constraint],		                                colm2_name datatype[size]…					.					.			 	              [table level constraints]			              [ON COMMIT clause] or [ON UPDATE clause] };Constraints enforce certain rules on the table to maintain data integrity and quality.
4NAMING CONVENTIONSWithin the table definition the user has to specify :Table name.Column name.Column data type.Size of the column.Constraint [ if any].The naming conventions for the table name and column names are:Must begin with a character(either in lower or upper case) and may be up to 30 characters long.Can contain a combination of alphabets(A-Z & a-z), numbers(0-9),_,   $ and #.Must not be a previously specified name for another oracle object owned by the same user and must not be an Oracle reserved keyword.
5DATATYPESFollowing the column name every column must be specified with a data type. Data types provided by Oracle are:
6CONSTRAINTS
7THE CREATE COMMANDAnother keyword “DEFAULT” is used to specify the value to be inserted if the user does not enter a value.
8THE CREATE COMMANDConstraints can be given a name or the Oracle server itself names the contraints in a SYS_Cn format where n stands for the constraint number.To name a constraint the syntax is :CREATE TABLE TABLE_NAME(colm1_name datatype[size] [CONSTRAINT] constraint_name1 constraint,						column level constraint..CONSTRAINT constraint_name2 constraint(colm2_name));table level constraintConstraints can either be defined at column level or table level.You can notice that constraint_name1 is defined at a column level and constraint_name2 is defined at a table level. All constraints except “NOT NULL” can be defined at table level.
9EXAMPLE TABLE CREATIONTo get a better grasp of things let us create a set of example tables covering one by one the points leant in the previous slides:EXAMPLE 1:CREATE TABLE MySchema.InfoTable (	name varchar2(15), 				age number(3), 				phone number(10)	   );
10TABLE WITH CONSTRAINTSThe previous table contained no constraints .We will create a new table with the following constraints:
11TABLE WITH CONSTRAINTSThe SQL code for creating the above table is:CREATE TABLE ConTable	(	ID number(5),	name varchar2(15)CONSTRAINTS ConTable_name NOT NULL,	age number(3) DEFAULT 18,	phone number(10)CONSTRAINTS ConTable_phone_unique UNIQUE,	city varchar2(15)CONSTRAINTS ConTable_city_check	CHECK(city IN( ‘MUMBAI’,’PUNE’,’HYDERABAD’)),	CONSTRAINTSConTable_pk PRIMARY KEY (ID),ConTable_fk FOREIGN KEY(ID) REFERENCES CustDetails(ID)	); 	     Here we have defined NOT NULL constraint at a column level while the PRIMARY KEY 	    	     constraint at the table level.
12CREATING TABLES USING THE AS CLAUSE (SUBQUERY)In the previous examples we have created tables but not populated them.There a method of creating tables and populating them with data from other tables.It is the method of using subqueries:SYNTAX:CREATE TABLE TABLE_NAME (colm_namedatatype(size) [constraint]…			…			.. )ASSUBQUERY(the SELECT statement);
13CREATING TABLES USING THE AS CLAUSE (SUBQUERY)Consider the table in EXAMPLE1 to be populated with the data:Now we will create a table InfoTable40 and populate it with data from the above table. EXAMPLE3:CREATE TABLE InfoTable40AS( SELECT * FROM Infotable WHERE age=40);On viewing the data in InfoTable40 we see:i.e.  It contains the rows from InfoTable with age = 40 as per the SELECT subquery.Hence we have created and populated a table in one statement.
14ALTERING TABLESOnce a table is created it structure can be altered using the ALTER command.Using the alter command we canAdd a column or constraint or Default value.Modify a column.Delete a column.The ALTER command can be used along with the following keywords:
15ALTERING THE EXAMPLE TABLE	The SYNTAX for ALTER command is:ALTER TABLE TABLE_NAME [ADD/MODIFY/DROP] (colm_namedatatype[size] [constraint]);Consider the EXAMPLE1 table InfoTable:We will alter the table in three steps:First modify the precision of “age” column to 4.Add a new column “city”.Drop the column “phone” .
16ALTERING TABLESMODIFYING:ALTER TABLE InfoTable MODIFY(age number(4) DEFAULT 20);ADDING:ALTER TABLE InfoTable ADD(city varchar2(15));DROPPING:ALTER TABLE InfoTable drop(phone);
17DROPPING TABLESOnce a tables is created and populated, we can drop the table using the DROP command.Once the DROP command has been exercised :It cannot be reversed and the data and structure are lost permanently Also dropping a table renders the views and indexed referring to the table invalid.Also drops the all its constraints.The SYNTAX for the DROP command is:DROP TABLE TABLE_NAME;EXAMPLE:DROP TABLE InfoTable;DESC InfoTable;
18CREATING OTHER ORACLE OBJECTSThe CREATE command can not only be used to create tables but also other database objects like views, indexes and sequences.
19CREATING A VIEWA view is a logical representation of a subset of data from one or more tables/views.The advantages of a view are:Restrict data access.Simplifying queries for the end user.Displaying the same data in different views.A view can be updatable (manipulate base table using view) or a read only view.A view can be created using a CREATE command.The SYNTAX to create a view is:CREATE  [OR REPLACE] VIEW VIEW_NAME[ alias , alias…]AS SUBQUERY                     a select statement[WITH CHECK OPTION]      specifies the only the rows displayable in the view can be inserted or updated[WITH READ ONLY]             specifies the DML operations cannot be performed using the view.
20EXAMPLE VIEW CREATIONCREATE VIEW InfoTable_ViewASSELECT * FROM InfoTable WHERE age = 40;SELECT * FROM InfoTable_View;VIEW WITH ALIAS:CREATE VIEW InfoTable_ViewAliasASSELECT name ENAME,ageEAGE,phone CONTACT_NO FROM InfoTable WHERE age = 40;SELECT * FROM InfoTable_ViewAlias ;
21ALTERING AND DROPPING A VIEWALTERING the InfoTable_View view:CREATE OR REPLACE VIEW InfoTable_ViewASSELECT * FROM InfoTable WHERE age > 40; SELECT * FROM InfoTable_View;DROPPING A VIEW:DROP VIEW InfoTable_View;SELECT * FROM InfoTable_View;
22CREATING AN SEQUENCEA sequence is an object that can generate a series of numbers.A sequence can be shared by other objects and it speeds up accessing a sequence if cached in memory.The basic syntax to create an sequence is:CREATE SEQUENCE SEQUENCE_NAME[INCREMENT BY n]		- value by which it must be incremented[START WITH n]		- value from which sequence generation must begin.[MINVALUE n]		- specifies a maximum value the sequence can generate. Default is 10^26 for ascending 			   sequence and 1 for descending sequence.[MAXVALUE n]		- specified the minimum value for a sequence generate. Default is 1 for ascending sequence 			   and 10^26 for descending sequence.[CYCLE / NOCYCLE ]		- specifies whether once maximum value is reached can it cycle from the start value.[CACHE n / NOCACHE ]	- specifies how many sequence values can be stored in the cache for quick access.	        Once a sequence is created we can assess it using two methods:CURRVAL : returns the current value of the sequence number.NEXTVAL : returns the next value in the sequence and it returns a unique value even when being used by multiple tables.
23EXAMPLE SEQUENCEWe create an example sequence.CREATE SEQUENCE ascseqINCREMENT BY 5MAXVALUE 100CYCLENOCACHE;The above sequence an be accessed by ascseq.currval or ascseq.nextval and can be used to generate a primary key.USAGE IN A TABLE:INSERT INTO ConTable VALUES(ascseq.nextval,'bill' ,40,9000666000 ,'PUNE' );
24ALTERING AND DROPPING SEQUENCETo alter a sequence we use the ALTER commnad.SYNTAX:					EXAMPLE:ALTER SEQUENCE SEQUENCE_NAME		ALTER SEQUENCE ascseq[INCREMENT BY n]				INCREMENT BY 10		[MINVALUE n] 					[MAXVALUE n]			 	MAXVALUE 200	[CYCLE / NOCYCLE ]				NOCYCLE 		[CACHE n / NOCACHE ];			CACHE 10;The START WITH parameter cannot be altered once a sequence is created.nly future values will be affected. Hence the MAXVALUE must be greater than at least the value last generated.DROPPING A SEQUENCE:			EXAMPLE:DROP SEQUENCE SEQUENCE_NAME;		DROP SEQUENCE ascseq;
25CREATING AN INDEXAn index is an object that creates a rapid path of access to the rows of specified tables and helps in improving the retrieval of data .The index is independent of the table and is used and maintained by the Oracle server.Oracle server automatically creates indexes on columns of a table having Primary key or Unique  as constraints. Users can manually create Indexes for other non key columns.SYNTAX:						Index on phone column:CREATE INDEX INDEX_NAME				CREATE INDEX ConTable_IdxON TABLE_NAME( column1,…[column n]);		ON ConTable (phone);DROPPING AN INDEX:DROP INDEX INDEX_NAME;				DROP INDEX ConTable_Idx;Create an Index only when the column contains a large number of rows, is frequently used and is present in queries returning a large number of rows to avoid wastage of resources.
THANK YOU26THANK YOU FOR VIEWING THIS PRESENTATIONFOR MORE PRESENTATIONS AND VIDEOS ON ORACLE AND DATAMINING ,please visit:  www.dataminingtools.net

More Related Content

What's hot (20)

PPTX
Lecture 4 sql {basics keys and constraints}
Shubham Shukla
 
PPT
PL/SQL Introduction and Concepts
Bharat Kalia
 
PPT
Files in c++ ppt
Kumar
 
PPTX
Data structure and its types.
buyinstagramfollowersaustralia
 
PPTX
Oraclesql
Priya Goyal
 
PPTX
Data structure & its types
Rameesha Sadaqat
 
PPTX
trigger dbms
kuldeep100
 
PPTX
Packages in PL/SQL
Pooja Dixit
 
PPTX
Sql subquery
Raveena Thakur
 
PPTX
Classification of datastructure.ppt
LakshmiSamivel
 
PPTX
Pointer in C++
Mauryasuraj98
 
PPTX
database language ppt.pptx
Anusha sivakumar
 
PPTX
Introduction to PL/SQL
Kailash N
 
PPTX
PLSQL Tutorial
Quang Minh Đoàn
 
PPTX
Relational database
Megha Sharma
 
PPTX
SQL commands
GirdharRatne
 
PPTX
SQL JOIN
Ritwik Das
 
PPTX
Lab2 ddl commands
Balqees Al.Mubarak
 
Lecture 4 sql {basics keys and constraints}
Shubham Shukla
 
PL/SQL Introduction and Concepts
Bharat Kalia
 
Files in c++ ppt
Kumar
 
Data structure and its types.
buyinstagramfollowersaustralia
 
Oraclesql
Priya Goyal
 
Data structure & its types
Rameesha Sadaqat
 
trigger dbms
kuldeep100
 
Packages in PL/SQL
Pooja Dixit
 
Sql subquery
Raveena Thakur
 
Classification of datastructure.ppt
LakshmiSamivel
 
Pointer in C++
Mauryasuraj98
 
database language ppt.pptx
Anusha sivakumar
 
Introduction to PL/SQL
Kailash N
 
PLSQL Tutorial
Quang Minh Đoàn
 
Relational database
Megha Sharma
 
SQL commands
GirdharRatne
 
SQL JOIN
Ritwik Das
 
Lab2 ddl commands
Balqees Al.Mubarak
 

Viewers also liked (20)

PPT
SQL DDL
Vikas Gupta
 
PDF
Part 6 ddl dan dml (case studiies)
Denny Yahya
 
PPT
DDL DML sysytems
bhujendhar05
 
PPTX
DBMS information in detail || Dbms (lab) ppt
gourav kottawar
 
PPTX
Data definition language (ddl)
Dex Winadha
 
PDF
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
eVideoTuition
 
PDF
Part 7 ddl dan dml lant..retriving data up
Denny Yahya
 
PPTX
Sql joins inner join self join outer joins
Deepthi Rachumallu
 
PPT
Types Of Join In Sql Server - Join With Example In Sql Server
programmings guru
 
PDF
SQL Joins and Query Optimization
Brian Gallagher
 
PDF
Huidige status van de testtaal TTCN-3
Erik Altena
 
PPTX
R Statistics
DataminingTools Inc
 
PPT
Association Rules
DataminingTools Inc
 
PPTX
LISP: Scope and extent in lisp
DataminingTools Inc
 
DOC
建築師法修正草案總說明
Filip Yang
 
PPTX
MS SQL SERVER: Microsoft naive bayes algorithm
DataminingTools Inc
 
PPTX
Txomin Hartz Txikia
irantzugoitia86
 
SQL DDL
Vikas Gupta
 
Part 6 ddl dan dml (case studiies)
Denny Yahya
 
DDL DML sysytems
bhujendhar05
 
DBMS information in detail || Dbms (lab) ppt
gourav kottawar
 
Data definition language (ddl)
Dex Winadha
 
Oracle/SQL For Beginners - DDL | DML | DCL | TCL - Quick Learning
eVideoTuition
 
Part 7 ddl dan dml lant..retriving data up
Denny Yahya
 
Sql joins inner join self join outer joins
Deepthi Rachumallu
 
Types Of Join In Sql Server - Join With Example In Sql Server
programmings guru
 
SQL Joins and Query Optimization
Brian Gallagher
 
Huidige status van de testtaal TTCN-3
Erik Altena
 
R Statistics
DataminingTools Inc
 
Association Rules
DataminingTools Inc
 
LISP: Scope and extent in lisp
DataminingTools Inc
 
建築師法修正草案總說明
Filip Yang
 
MS SQL SERVER: Microsoft naive bayes algorithm
DataminingTools Inc
 
Txomin Hartz Txikia
irantzugoitia86
 
Ad

Similar to Oracle: DDL (20)

PDF
Intruduction to SQL.Structured Query Language(SQL}
IlgarKarimov3
 
PPTX
Less08_Schema Advanced Databases and Management.pptx
MurtazaMughal13
 
PPT
15925 structured query
Universitas Bina Darma Palembang
 
PPT
Lec 1 = introduction to structured query language (sql)
Faisal Anwar
 
DOC
Oracle SQL AND PL/SQL
suriyae1
 
PPT
Introduction to Structured Query Language (SQL).ppt
JohnnySebastian4
 
PPT
SQL WORKSHOP::Lecture 10
Umair Amjad
 
PPT
Introduction to Structured Query Language (SQL) (1).ppt
ComputerScienceDepar6
 
PPT
DDL. data defination language for creating database
SHAKIR325211
 
PPTX
Relational Database Language.pptx
Sheethal Aji Mani
 
PPT
Les10
arnold 7490
 
PPT
Les10[1]Creating and Managing Tables
siavosh kaviani
 
PPTX
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
deeptanshudas100
 
PPT
Introduction to structured query language (sql)
Sabana Maharjan
 
PDF
Rdbms day3
Nitesh Singh
 
PPT
Oracle Sql & PLSQL Complete guide
Raviteja Chowdary Adusumalli
 
PPT
Sql tables
divyas177
 
PPT
Sql tables
Ranidm
 
PDF
DBMS_ddlVFSBFSBS22222222222222222222222222222222222
227567
 
PDF
STRUCTURED QUERY LANGUAGE
SarithaDhanapal
 
Intruduction to SQL.Structured Query Language(SQL}
IlgarKarimov3
 
Less08_Schema Advanced Databases and Management.pptx
MurtazaMughal13
 
15925 structured query
Universitas Bina Darma Palembang
 
Lec 1 = introduction to structured query language (sql)
Faisal Anwar
 
Oracle SQL AND PL/SQL
suriyae1
 
Introduction to Structured Query Language (SQL).ppt
JohnnySebastian4
 
SQL WORKSHOP::Lecture 10
Umair Amjad
 
Introduction to Structured Query Language (SQL) (1).ppt
ComputerScienceDepar6
 
DDL. data defination language for creating database
SHAKIR325211
 
Relational Database Language.pptx
Sheethal Aji Mani
 
Les10[1]Creating and Managing Tables
siavosh kaviani
 
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
deeptanshudas100
 
Introduction to structured query language (sql)
Sabana Maharjan
 
Rdbms day3
Nitesh Singh
 
Oracle Sql & PLSQL Complete guide
Raviteja Chowdary Adusumalli
 
Sql tables
divyas177
 
Sql tables
Ranidm
 
DBMS_ddlVFSBFSBS22222222222222222222222222222222222
227567
 
STRUCTURED QUERY LANGUAGE
SarithaDhanapal
 
Ad

More from DataminingTools Inc (20)

PPTX
Terminology Machine Learning
DataminingTools Inc
 
PPTX
Techniques Machine Learning
DataminingTools Inc
 
PPTX
Machine learning Introduction
DataminingTools Inc
 
PPTX
Areas of machine leanring
DataminingTools Inc
 
PPTX
AI: Planning and AI
DataminingTools Inc
 
PPTX
AI: Logic in AI 2
DataminingTools Inc
 
PPTX
AI: Logic in AI
DataminingTools Inc
 
PPTX
AI: Learning in AI 2
DataminingTools Inc
 
PPTX
AI: Learning in AI
DataminingTools Inc
 
PPTX
AI: Introduction to artificial intelligence
DataminingTools Inc
 
PPTX
AI: Belief Networks
DataminingTools Inc
 
PPTX
AI: AI & Searching
DataminingTools Inc
 
PPTX
AI: AI & Problem Solving
DataminingTools Inc
 
PPTX
Data Mining: Text and web mining
DataminingTools Inc
 
PPTX
Data Mining: Outlier analysis
DataminingTools Inc
 
PPTX
Data Mining: Mining stream time series and sequence data
DataminingTools Inc
 
PPTX
Data Mining: Mining ,associations, and correlations
DataminingTools Inc
 
PPTX
Data Mining: Graph mining and social network analysis
DataminingTools Inc
 
PPTX
Data warehouse and olap technology
DataminingTools Inc
 
PPTX
Data Mining: Data processing
DataminingTools Inc
 
Terminology Machine Learning
DataminingTools Inc
 
Techniques Machine Learning
DataminingTools Inc
 
Machine learning Introduction
DataminingTools Inc
 
Areas of machine leanring
DataminingTools Inc
 
AI: Planning and AI
DataminingTools Inc
 
AI: Logic in AI 2
DataminingTools Inc
 
AI: Logic in AI
DataminingTools Inc
 
AI: Learning in AI 2
DataminingTools Inc
 
AI: Learning in AI
DataminingTools Inc
 
AI: Introduction to artificial intelligence
DataminingTools Inc
 
AI: Belief Networks
DataminingTools Inc
 
AI: AI & Searching
DataminingTools Inc
 
AI: AI & Problem Solving
DataminingTools Inc
 
Data Mining: Text and web mining
DataminingTools Inc
 
Data Mining: Outlier analysis
DataminingTools Inc
 
Data Mining: Mining stream time series and sequence data
DataminingTools Inc
 
Data Mining: Mining ,associations, and correlations
DataminingTools Inc
 
Data Mining: Graph mining and social network analysis
DataminingTools Inc
 
Data warehouse and olap technology
DataminingTools Inc
 
Data Mining: Data processing
DataminingTools Inc
 

Recently uploaded (20)

PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 

Oracle: DDL

  • 1. 1Using ORACLE®Data Definition Language(Creating our sample database) Indexes and Views
  • 2. 2DATA DEFINATION LANGUAGEData Definition language abbreviated as DDL refers to the set of commands used to define the data containers in Oracle like Tables and also defining Views and Indexes.Basically there are 3 DDL commands viz:
  • 3. 3THE CREATE COMMANDThe “CREATE” command can be used to create a table, view, index etc.Let us look at creating a table:In order to create a table a user must have the privileges to create tables i.e. The “CREATE TABLE” privilege.The basic syntax to create a table is :CREATE TABLE [schema.]TABLENAME ( colm1_name datatype[size] [colm_level_constraint], colm2_name datatype[size]… . . [table level constraints] [ON COMMIT clause] or [ON UPDATE clause] };Constraints enforce certain rules on the table to maintain data integrity and quality.
  • 4. 4NAMING CONVENTIONSWithin the table definition the user has to specify :Table name.Column name.Column data type.Size of the column.Constraint [ if any].The naming conventions for the table name and column names are:Must begin with a character(either in lower or upper case) and may be up to 30 characters long.Can contain a combination of alphabets(A-Z & a-z), numbers(0-9),_, $ and #.Must not be a previously specified name for another oracle object owned by the same user and must not be an Oracle reserved keyword.
  • 5. 5DATATYPESFollowing the column name every column must be specified with a data type. Data types provided by Oracle are:
  • 7. 7THE CREATE COMMANDAnother keyword “DEFAULT” is used to specify the value to be inserted if the user does not enter a value.
  • 8. 8THE CREATE COMMANDConstraints can be given a name or the Oracle server itself names the contraints in a SYS_Cn format where n stands for the constraint number.To name a constraint the syntax is :CREATE TABLE TABLE_NAME(colm1_name datatype[size] [CONSTRAINT] constraint_name1 constraint, column level constraint..CONSTRAINT constraint_name2 constraint(colm2_name));table level constraintConstraints can either be defined at column level or table level.You can notice that constraint_name1 is defined at a column level and constraint_name2 is defined at a table level. All constraints except “NOT NULL” can be defined at table level.
  • 9. 9EXAMPLE TABLE CREATIONTo get a better grasp of things let us create a set of example tables covering one by one the points leant in the previous slides:EXAMPLE 1:CREATE TABLE MySchema.InfoTable ( name varchar2(15), age number(3), phone number(10) );
  • 10. 10TABLE WITH CONSTRAINTSThe previous table contained no constraints .We will create a new table with the following constraints:
  • 11. 11TABLE WITH CONSTRAINTSThe SQL code for creating the above table is:CREATE TABLE ConTable ( ID number(5), name varchar2(15)CONSTRAINTS ConTable_name NOT NULL, age number(3) DEFAULT 18, phone number(10)CONSTRAINTS ConTable_phone_unique UNIQUE, city varchar2(15)CONSTRAINTS ConTable_city_check CHECK(city IN( ‘MUMBAI’,’PUNE’,’HYDERABAD’)), CONSTRAINTSConTable_pk PRIMARY KEY (ID),ConTable_fk FOREIGN KEY(ID) REFERENCES CustDetails(ID) ); Here we have defined NOT NULL constraint at a column level while the PRIMARY KEY constraint at the table level.
  • 12. 12CREATING TABLES USING THE AS CLAUSE (SUBQUERY)In the previous examples we have created tables but not populated them.There a method of creating tables and populating them with data from other tables.It is the method of using subqueries:SYNTAX:CREATE TABLE TABLE_NAME (colm_namedatatype(size) [constraint]… … .. )ASSUBQUERY(the SELECT statement);
  • 13. 13CREATING TABLES USING THE AS CLAUSE (SUBQUERY)Consider the table in EXAMPLE1 to be populated with the data:Now we will create a table InfoTable40 and populate it with data from the above table. EXAMPLE3:CREATE TABLE InfoTable40AS( SELECT * FROM Infotable WHERE age=40);On viewing the data in InfoTable40 we see:i.e. It contains the rows from InfoTable with age = 40 as per the SELECT subquery.Hence we have created and populated a table in one statement.
  • 14. 14ALTERING TABLESOnce a table is created it structure can be altered using the ALTER command.Using the alter command we canAdd a column or constraint or Default value.Modify a column.Delete a column.The ALTER command can be used along with the following keywords:
  • 15. 15ALTERING THE EXAMPLE TABLE The SYNTAX for ALTER command is:ALTER TABLE TABLE_NAME [ADD/MODIFY/DROP] (colm_namedatatype[size] [constraint]);Consider the EXAMPLE1 table InfoTable:We will alter the table in three steps:First modify the precision of “age” column to 4.Add a new column “city”.Drop the column “phone” .
  • 16. 16ALTERING TABLESMODIFYING:ALTER TABLE InfoTable MODIFY(age number(4) DEFAULT 20);ADDING:ALTER TABLE InfoTable ADD(city varchar2(15));DROPPING:ALTER TABLE InfoTable drop(phone);
  • 17. 17DROPPING TABLESOnce a tables is created and populated, we can drop the table using the DROP command.Once the DROP command has been exercised :It cannot be reversed and the data and structure are lost permanently Also dropping a table renders the views and indexed referring to the table invalid.Also drops the all its constraints.The SYNTAX for the DROP command is:DROP TABLE TABLE_NAME;EXAMPLE:DROP TABLE InfoTable;DESC InfoTable;
  • 18. 18CREATING OTHER ORACLE OBJECTSThe CREATE command can not only be used to create tables but also other database objects like views, indexes and sequences.
  • 19. 19CREATING A VIEWA view is a logical representation of a subset of data from one or more tables/views.The advantages of a view are:Restrict data access.Simplifying queries for the end user.Displaying the same data in different views.A view can be updatable (manipulate base table using view) or a read only view.A view can be created using a CREATE command.The SYNTAX to create a view is:CREATE [OR REPLACE] VIEW VIEW_NAME[ alias , alias…]AS SUBQUERY a select statement[WITH CHECK OPTION] specifies the only the rows displayable in the view can be inserted or updated[WITH READ ONLY] specifies the DML operations cannot be performed using the view.
  • 20. 20EXAMPLE VIEW CREATIONCREATE VIEW InfoTable_ViewASSELECT * FROM InfoTable WHERE age = 40;SELECT * FROM InfoTable_View;VIEW WITH ALIAS:CREATE VIEW InfoTable_ViewAliasASSELECT name ENAME,ageEAGE,phone CONTACT_NO FROM InfoTable WHERE age = 40;SELECT * FROM InfoTable_ViewAlias ;
  • 21. 21ALTERING AND DROPPING A VIEWALTERING the InfoTable_View view:CREATE OR REPLACE VIEW InfoTable_ViewASSELECT * FROM InfoTable WHERE age > 40; SELECT * FROM InfoTable_View;DROPPING A VIEW:DROP VIEW InfoTable_View;SELECT * FROM InfoTable_View;
  • 22. 22CREATING AN SEQUENCEA sequence is an object that can generate a series of numbers.A sequence can be shared by other objects and it speeds up accessing a sequence if cached in memory.The basic syntax to create an sequence is:CREATE SEQUENCE SEQUENCE_NAME[INCREMENT BY n] - value by which it must be incremented[START WITH n] - value from which sequence generation must begin.[MINVALUE n] - specifies a maximum value the sequence can generate. Default is 10^26 for ascending sequence and 1 for descending sequence.[MAXVALUE n] - specified the minimum value for a sequence generate. Default is 1 for ascending sequence and 10^26 for descending sequence.[CYCLE / NOCYCLE ] - specifies whether once maximum value is reached can it cycle from the start value.[CACHE n / NOCACHE ] - specifies how many sequence values can be stored in the cache for quick access. Once a sequence is created we can assess it using two methods:CURRVAL : returns the current value of the sequence number.NEXTVAL : returns the next value in the sequence and it returns a unique value even when being used by multiple tables.
  • 23. 23EXAMPLE SEQUENCEWe create an example sequence.CREATE SEQUENCE ascseqINCREMENT BY 5MAXVALUE 100CYCLENOCACHE;The above sequence an be accessed by ascseq.currval or ascseq.nextval and can be used to generate a primary key.USAGE IN A TABLE:INSERT INTO ConTable VALUES(ascseq.nextval,'bill' ,40,9000666000 ,'PUNE' );
  • 24. 24ALTERING AND DROPPING SEQUENCETo alter a sequence we use the ALTER commnad.SYNTAX: EXAMPLE:ALTER SEQUENCE SEQUENCE_NAME ALTER SEQUENCE ascseq[INCREMENT BY n] INCREMENT BY 10 [MINVALUE n] [MAXVALUE n] MAXVALUE 200 [CYCLE / NOCYCLE ] NOCYCLE [CACHE n / NOCACHE ]; CACHE 10;The START WITH parameter cannot be altered once a sequence is created.nly future values will be affected. Hence the MAXVALUE must be greater than at least the value last generated.DROPPING A SEQUENCE: EXAMPLE:DROP SEQUENCE SEQUENCE_NAME; DROP SEQUENCE ascseq;
  • 25. 25CREATING AN INDEXAn index is an object that creates a rapid path of access to the rows of specified tables and helps in improving the retrieval of data .The index is independent of the table and is used and maintained by the Oracle server.Oracle server automatically creates indexes on columns of a table having Primary key or Unique as constraints. Users can manually create Indexes for other non key columns.SYNTAX: Index on phone column:CREATE INDEX INDEX_NAME CREATE INDEX ConTable_IdxON TABLE_NAME( column1,…[column n]); ON ConTable (phone);DROPPING AN INDEX:DROP INDEX INDEX_NAME; DROP INDEX ConTable_Idx;Create an Index only when the column contains a large number of rows, is frequently used and is present in queries returning a large number of rows to avoid wastage of resources.
  • 26. THANK YOU26THANK YOU FOR VIEWING THIS PRESENTATIONFOR MORE PRESENTATIONS AND VIDEOS ON ORACLE AND DATAMINING ,please visit: www.dataminingtools.net