Professional Documents
Culture Documents
RDBMS - Unit 3 - Notes
RDBMS - Unit 3 - Notes
BCom CA SEM-3
Unit - 3
Table of Contents
SQL stands for Structured Query Language. It is sometimes called as SEQUEL (Structured English Query Language).
SQL is a query language used for accessing and modifying information in the database. That is, it lets us access and
manipulate databases.
SQL is an ANSI (American National Standards Institute) standard
Few of the SQL commands used in SQL programming are SELECT Statement, UPDATE Statement, INSERT INTO
Statement, DELETE Statement, WHERE Clause, ORDER BY Clause, GROUP BY Clause, Joins, Views, GROUP Functions,
Indexes etc
SQL is a non-procedural, English-like language that processes data in groups of records. Few functions of SQL are:
Create tables and other database objects
Store Data
Modify Data
Retrieve Data
Delete Data
3.1.1 SQL Terminology
Catalog: A catalog is a directory of information about data sets, files, or a database. It usually describes where a data set,
file or database entity is located and may also include other information, such as the type of device on which each data
set or file is stored
Schema: A database schema is a structure that contains description of objects created by a user such as tables, views,
stored procedures etc. We can assign login permissions to a single schema to a user so that the user can only access the
objects they are authorized to access
Data Definition Language (DDL): DDL is a set of commands that are used to create and modify the structure of database
objects in database (i.e. creating, altering, dropping tables and establishing constraints)
Data Manipulation Language (DML): DML is a set of commands that are used to store (insert), retrieve, modify (update)
or delete data in database
Data Control Language (DCL): DCL is a set of commands used to control access to data stored in a database
(Authorization). It includes commands for administering user privileges
Transaction Control Language (TCL): TCL is a set of commands used to manage transactions in database. These are used
to manage the changes made by DML statements. It also allows statements to be grouped together into logical
transactions
Many RDBMS are available on many operating system platforms including WINDOWS and UNIX. Oracle is a popular
example of an RDBMS. Even the Data Dictionary is simply a collection of tables of data along with indexes and other
objects such as sequences and triggers that are created using SQL
SQL has a basic grammar and syntax
The functionality of the SQL language is virtually identical across all the operating system platforms
For using SQL, one does not require programming experience. But if one has, it can help them to conceptualize
what a particular SQL command will help to execute and retrieve SQL queries that result data using SELECT, FROM,
WHERE and ORDER BY commands.
SQL supports basic data structures and operations that allow the user to design (create), access (retrieve), maintain
(update, delete), control and protect data in database.
Well Defined Standards Exist: SQL databases use long-established standard, which is being adopted by ANSI & ISO.
Non-SQL databases do not adhere to any clear standard. Hence, SQL works with database programs like DB2, Oracle,
MS Access, Sybase, and MS SQL Server etc.
Reduced Training Costs: Using standard SQL it is easier to manage database systems without having to write
substantial amount of code.
High Speed: SQL Queries can be used to retrieve large amounts of records from a database quickly and efficiently.
Portability of applications and database definition: It is easy to move database applications and database definition
from one machine to another
Increased Productivity: SQL is very simple and easy to learn. Hence, DB programmers can become proficient in its
use.
Application Longevity: An Application designed using SQL tends to remain standard for a long time
Reduced dependence on a single vendor: Since SQL is a standard query language that works with many database
programs (like DB2, Oracle, MS Access, Sybase, and MS SQL Server), hence there is no dependence on a single
vendor
Emergence of ORDBMS: Previously SQL databases were synonymous with relational database. With the emergence
of Object Oriented DBMS, object storage capabilities are extended to relational databases.
The schema of a database system is its structure described in a formal language (like SQL) supported by the
database management system (DBMS)
The term "schema" refers to the organization of data as a blueprint of how the database is constructed (divided into
database tables in the case of relational databases)
The formal definition of a database schema is a set of formulas (sentences) called integrity constraints imposed on a
database. It can contain formulas representing integrity constraints specifically for an application and the constraints
specifically for a type of database, all expressed in the same database language.
In a relational database, the schema defines the tables, fields, relationships, views, indexes, procedures, functions,
triggers, sequences, materialized views, synonyms, XML schemas, and other elements.
A database generally stores its schema in a data dictionary. Although a schema is defined in text database language,
the term is often used to refer to a graphical depiction of the database structure.
In other words, schema is the structure of the database that defines the objects in the database
Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices,
etc. It defines how the data will be stored in a secondary storage.
Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It
defines tables, views, and integrity constraints.
The Data Schema (or simply “schema”) and Database are different. A schema contains a group of tables whereas a
database contains a group of schemas.
Data Schema
Schema is a logical structure defined to store data in Database. A schema defines attributes of the database such as
tables and its properties (columns).
A schema is the set of metadata (data dictionary) used by the database (generated using DDL). A database schema is
a description of the data in a database. Simply we can consider a schema to be a user account and collection of all
objects within it
Database
A Database is a collection of inter-related data. It is a memory component to store Data, connected to a computer
installed with DBMS Software (such as Oracle, MySQL etc).
A database is the thing that contains all the schemas we create and their data (plus a bunch of predefined system
users, tables, views, etc. that make the whole things work).
A table is a collection of related data held in a structured format within a database. It consists of columns, and rows.
In relational databases, and flat file databases, a table is a set of data elements (values) using a model of vertical
columns (identifiable by name) and horizontal rows, the cell being the unit where a row and column intersect.
A table has a specified number of columns, but can have any number of rows.
Each row is identified by the values in one or more columns.
A specific set of columns which uniquely identify a row is called the primary key.
A data type specifies a particular type of data such as integer, floating-point, Boolean (true or false) etc.
A data type also specifies the possible values for that type, the operations that can be performed on that type and
the way the values of that type are stored. For Ex: Oracle treats values of one data type differently from values of
another by using a set of properties
Data stored in a relational database can be stored using a variety of data types. SQL provides many predefined data
types and subtypes. The primary oracle data types are NUMBER, CHAR and VARCHAR for storing numbers and text
data
Following are the Key Data Types in SQL:
CHAR:
VARCHAR:
VARCHAR2:
SQL commands help the user to interact with SQL application and the database and pass instructions to perform
specific task that work with data to create, update or manage the database
SQL commands can be used not only for searching the database but also to perform various other functions like, for
example, we can create tables, add data to tables, modify data, drop the table or set permissions for users.
SQL commands provide access for the structure and also the data part of the tables.
SQL commands are grouped into 4 major categories depending on their functionality. Following is their overview:
Data Definition Language (DDL) deals with database schemas and descriptions of how the data should reside in the
database
DDL commands are used to create, modify and delete the structure of the object in the database
The syntax of DDL command includes TABLE keyword after the command name. Following are the DDL commands:
i) CREATE
The CREATE TABLE statement allows us to create structure of the table and specify all the required columns,
their data type and size of the columns (to store data).
Data type is used to specify the type of data to be stored in the selected column
Size specifies the number of elements inside the column
Integrity Constraints (entry level rules to ensure data integrity) like primary key, unique key, foreign key can
be defined for the selected columns while creating the table
Syntax: The syntax for the CREATE TABLE statement in SQL is:
Example:
ii) DESCRIBE
iii) ALTER
The ALTER TABLE command is used to change the definition (structure) of an existing table by modifying the
definition of its columns
The ALTER command is used to perform the following functions:
i) Add, modify or drop columns of a table
ii) Add and drop constraints
iii) Enable and Disable constraints
Example to add a new column: To add a column “phno” to the student table, the query would be as follows:
ALTER TABLE student add(phno number(10));
Example to modify an existing column: To modify the size of the column “name” to “25” in student table,
the query would be as follows:
ALTER TABLE student modify(Name varchar2(25));
iv) DROP
The DROP TABLE command is used to remove an object from the database (destroys a table structure)
The DROP command removes the table structure from the database including all the rows in the table
When a table is dropped all the references to the table will become invalid
v) RENAME
Example:
RENAME TABLE student TO s;
vi) TRUNCATE
The TRUNCATE command is used to delete all the rows from the table and free the space containing the
table
It removes all the rows of a table and commits the data in the table
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE student;
i) INSERT
INSERT command is used to enter and store the values in the database object in the defined order and type
(INSERT statement is used to add new rows of data to a table)
The data values given by the user in the insert statement should match with the data type declared for the
selected column
SQL INSERT command is implemented in 3 different methods. They are:
When above interactive insert statement is executed, DBMS interacts with the user as below
and user can insert multiple records (in this case, we are inserting 2 records):
ii) UPDATE
UPDATE command is used to edit or update the data values in a table based on conditions for the selected
record or field.
In the Update statement, WHERE clause identifies the rows that get affected. If the WHERE clause is not
implemented, column values for all the rows get affected
Update command is implemented using “set” keyword to overwrite the previous data values with currently
given values
The update command is used for multiple purposes as following:
To change the content (values) for the selected records
To enter the values for the fields which are left empty during insertion
To update the fields by performing calculations (such as sum, average)
To delete the data for the selected row/column by specifying empty values
Syntax:
Method1
UPDATE table_name SET column1=value1, column2=value2, …. [WHERE condition];
Method2
UPDATE table_name SET column1=expression1, column2=expression2, …. ;
Here,
table_name - is the table name which is being updated
Column1, column2, … - the columns whose values are being updated
Value1, value2, ... – are the new values being updated
Expression1, expression2, … - are the expressions that evaluate to new values being updated
iii) DELETE
DELETE statement is used to delete record(s) from a table based on user choice
It deletes either single record or multiple records based on conditions specified using “where” clause
Delete is used to remove only data records (not the fields/columns)
The WHERE clause in the DELETE command is optional and it identifies the rows in the column that gets
deleted. If the WHERE clause is not included, all the rows in the table are deleted
Syntax:
DELETE from table_name [WHERE condition];
Ex1: delete from student where name=’abc’;
Ex2: delete from student;
TRUNCATE is a DDL command which removes all rows from the table. It cannot be rolled back. Moreover, it
will clear the table space used by the rows.
iv) SELECT
Here,
Table_name is the name of the table from which the information is retrieved
Column1, column2, … includes one or more columns from which data is retrieved
The clauses mentioned with in the open brackets are optional
WHERE clause: It is used to post conditions and retrieve only selected records
ORDER BY clause: It is used to sort the result-set by a specified column (either by ascending or by
descending order)
GROUP BY clause: It is used to collect data across multiple records and group the results by one or more
columns
HAVING clause: It is used in combination with the GROUP BY clause to filter the records returned by GROUP
BY clause.
A select statement is used to display the records in multiple methods as
All rows and all columns
Selected columns and all rows
Selected rows with all columns
Selected rows with selected columns
Ex1: select * from student;
The above command displays all the records and fields from the student table
Ex2: select rollno, name, course from student;
The above command is used to display selected columns with all the records available in the table
Ex3: select * from student where rollno=3;
The above command is used to display all the columns for the record where the rollno of the student is
3 from student table (i.e. only selected records with all fields)
Ex4: select rollno, name, course from student where rollno=2;
The above command is used to display selected columns and selected records based on the condition.
i) GRANT
GRANT is a command used to provide access or privileges on the database objects to the users
GRANT privilege_name
ON object_name
TO {user_name | public | role_name}
[WITH GRANT OPTION];
Privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL,
CONNECT, SELECT, UPDATE, DELETE etc
Object_name is the name of a database object like TABLE, VIEW and SEQUENCE
User_name is the name of the user to whom privileges are granted
Public is used to grant access rights to all users
Role_name is a set of privileges granted to a role (group of users)
WITH GRANT OPTION – allows a user to grant access rights to other users
Example:
ii) REVOKE
REVOKE command is usually used by an administrator user to remove the database access from a user
which were previously granted
Syntax:
REVOKE privilege_name
ON object
FROM user_name;
i) COMMIT
The COMMIT command is the transactional command used to permanently save changes done by a
transaction in SQL to the database.
It saves all the transactions to the database since the last executed COMMIT or ROLLBACK command.
Syntax for committing a database transaction:
COMMIT [WORK];
ii) ROLLBACK
The ROLLBACK command is the transactional command used to undo transactions that have not already
been saved to the database.
It can only be used to undo transactions since the last COMMIT or ROLLBACK command issued.
Syntax for rolling back a database transaction:
ROLLBACK [WORK];
iii) SAVEPOINT
A SAVEPOINT is a point in a transaction up to which we can rollback the transaction without rolling back
the entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Examples:
SAVEPOINT SP1;
SAVEPOINT SP2;
The syntax for rolling back to a SAVEPOINT is as shown below:
ROLLBACK TO SAVEPOINT_NAME;
Example for rolling back to the SAVEPOINT named SP1:
ROLLBACK TO SP1;
The DUAL table is a special one-row, one-column table present by default in Oracle and other database installations.
In Oracle, this table has a single VARCHAR2(1) column called DUMMY that has a value of 'X'.
DUAL table is useful for computing a constant expression with the SELECT statement.
Example: It is suitable for selecting a pseudo column such as SYSDATE or USER as specified below:
An Operator is a symbol or a keyword which manipulates data items (called operands) and returns a result
Examples: The multiplication operator is represented by an asterisk (*), an operator that tests for nulls is
represented by the keywords IS NULL
There are two types of operators as mentioned below:
Operators which are used to perform Arithmetic Operations (mathematical calculations) in SQL are called Arithmetic
Operators
Following are the arithmetic operators in SQL:
A comparison (or relational) operator is a mathematical symbol which is used to compare two values.
Comparison operators are used in conditions that compare one expression with another. The result of a comparison
can be TRUE, FALSE, or UNKNOWN (an operator that has one or two NULL expressions returns UNKNOWN).
Following are the comparison operators in SQL:
The Logical operators are those that compare two conditions at a time to determine whether a row can be selected
for the output or not.
It returns a true or false value when combined with one or more true or false values.
When retrieving data using a SELECT statement, we can use logical operators in the WHERE clause
Following are the logical operators in SQL:
In the above example, NOT NULL specifies that column should always accept an explicit value of the given data
type. There are 2 columns where NOT NULL is not used which means these columns can contain a NULL value. A
field with a NULL value is one that has been left blank during record creation
Example: select * from emp where comm is NULL;
An aggregate function allows us to perform a calculation on a set of values to return a single scalar value
We often use aggregate functions with the GROUP BY and HAVING clauses of the SELECT statement
The following are the most commonly used SQL aggregate functions:
AGGREGATE_FUNCTION - is the name of the aggregate function (such as MIN, MAX, SUM, AVG or COUNT)
DISTINCT - specifies that the aggregate function should consider only distinct values of the argument expression
ALL - specifies that the aggregate function should consider all values including all duplicate values of the
argument expression. The default is ALL
EXPRESSION - Specifies a column, or any other expression, on which we want to perform the aggregation
Examples:
The ORDER BY keyword is used to sort the result-set (resulting records from a query) in ascending or descending
order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, we
need to use the DESC keyword.
Syntax: SELECT column1, column2, .. FROM tablename ORDER BY column1, column2, .. ASC|DESC;
Example: The following SQL statement selects all employees from the "EMP" table, sorted by the "JOB" column:
SELECT * FROM EMP ORDER BY JOB;
ORDER BY DESC Example: The following SQL statement selects all employees from the "EMP" table, sorted in the
Descending order by the "JOB" column: SELECT * FROM EMP ORDER BY JOB DESC;
The WHERE clause is used to filter records. It is used with conditional statements which use comparison operators
(such as =, <>, <, > etc)
The WHERE clause is used to extract only those records that fulfill a specified condition. Note: The WHERE clause is
not only used in SELECT statement, it is also used in UPDATE, DELETE statement, etc
Syntax: SELECT column1, column2, .. FROM tablename WHERE condition;
Example: The following SQL statement selects all the employees from the department with deptno "10", in the
"EMP" table: SELECT * FROM EMP WHERE deptno=10;
Example: The following SQL statement lists the number of employees working for each job
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions
(such as MIN, MAX, SUM etc). That is, SQL HAVING clause is “like a WHERE clause for aggregated data”
HAVING clause is always used with GROUP BY clause. That is, any column name appearing in the HAVING clause
must also appear in the GROUP BY clause.
HAVING clause Example: The following SQL statement lists the number of employees working for each job. Only
include those jobs with more than 2 employees:
SELECT COUNT(EMPNO), JOB FROM EMP GROUP BY JOB HAVING COUNT(EMPNO) > 2;
Example for sub query inside UPDATE statement: The following SQL statement updates the salary of employees
who belongs to department ‘SALES’. In this example, observe that 2 different tables are involved: the outer query
acts on EMP table where as inner query acts on DEPT table
update emp set sal=1800 where deptno = (select deptno from dept where dname='SALES');
Example for sub query inside INSERT statement: The following SQL statement inserts all the records available in the
table student1 into another table student2 (having the same structure as student1)
A correlated sub query is a SELECT statement nested inside another SQL statement, which contains a reference to
one or more columns in the outer query. That means, it is used to select data from a table referenced in the outer
query
The correlated sub query is dependent on the outer query for its execution. It cannot be executed independently (if
we try to execute it independently, it gives syntax error)
A query is called correlated sub query when both the inner query and the outer query are interdependent. For every
row processed by the inner query, the outer query is processed as well.
Example: In the following SQL statement, there is a parent-child relationship between dept & emp tables (deptno is
the primary key in dept table and foreign key in emp table). Here, the sub query contains a reference to one column
in the outer query (“e.deptno”). Hence, this sub query is a correlated sub query
select * from emp e where e.deptno = (select d.deptno from dept d where d.deptno = e.deptno);
An SQL JOIN clause combines rows from two or more tables. It creates a set of rows in a temporary table
A JOIN works on two or more tables if they have at least one common field and have a relationship between
them
JOIN keeps the base tables (structure and data) unchanged
Broadly, there are two types of SQL JOINS - NON EQUI JOIN and EQUI JOIN
The SQL NON EQUI JOIN is a join that uses comparison operator other than the equal sign like >, <, >=, <= for the
condition
The SQL EQUI JOIN is a simple SQL join uses the equal sign (=) as the comparison operator for the condition. It is of
two types - SQL Inner join and SQL Outer Join
Inner Join returns all the records satisfying the SQL equi-join condition specified
Example: Consider below 2 tables EMP and DEPT
DEPT
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
EMP
EMPNO ENAME SAL DEPTNO
7369 Smith 800 20
7499 Allen 1800 30
7521 Ward 1800 30
7566 Jones 2975 20
7654 Martin 1800
7698 Blake 1800
Output:
A Self Join is a special type of inner join where in a table is joined to itself (particularly when the table has a foreign
key that references its own primary key)
In a self join, we must define an alias for both copies of the table to avoid column ambiguity while referring them in
the query
Example: Assume we want to find all pairs of students residing in the same location from the below table Student.
Student:
Output:
This join returns all rows from both tables which satisfy the join condition along with rows which do not satisfy the
join condition from one of the
Outer joins are subdivided further into left outer joins, right outer joins and full outer joins depending on which
table’s rows are retained (left, right or both). In this case, left and right refer to the two sides of the JOIN keyword
The result of a left outer join (or simply left join) for table A and B always contains all records of the “left” table (A),
even if the join-condition does not find any matching record in the “right” table (B)
A left outer join returns all the rows from an inner join plus all rows in the left table that do not match to the right
table
Example : Consider the below 2 tables EMP and DEPT
EMP
EMPNO ENAME SAL DEPTNO
7369 Smith 800 20
7499 Allen 1800 30
7521 Ward 1800 30
7566 Jones 2975 20
7654 Martin 1800
7698 Blake 1800
DEPT
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
Query for Left Outer Join:
Output:
The result of a right outer join (or simply right join) for table A and B always contains all records of the “right” table
(B), even if the join-condition does not find any matching record in the “left” table (A)
A right outer join returns all the rows from an inner join plus all rows in the right table that do not match to the left
table
Example : Consider the below 2 tables EMP and DEPT
EMP
EMPNO ENAME SAL DEPTNO
7369 Smith 800 20
7499 Allen 1800 30
7521 Ward 1800 30
7566 Jones 2975 20
7654 Martin 1800
7698 Blake 1800
DEPT
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
Output:
EMPNO ENAME SAL DEPTNO DNAME
7369 Smith 800 20 RESEARCH
7499 Allen 1800 30 SALES
7521 Ward 1800 30 SALES
7566 Jones 2975 20 RESEARCH
10 ACCOUNTING
The result of a full outer join for table A and B combines the effect of applying both left and right outer joins
A full outer join returns all the rows from an inner join plus all rows in the left table that do not match to the right
table plus all rows in the right table that do not match to the left table
Example : Consider the below 2 tables EMP and DEPT
EMP
EMPNO ENAME SAL DEPTNO
7369 Smith 800 20
7499 Allen 1800 30
7521 Ward 1800 30
7566 Jones 2975 20
7654 Martin 1800
7698 Blake 1800
DEPT
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
Output:
A view is a predefined SQL statement (query) that is stored in the database with an associated name.
To reduce redundant data to the minimum possible, RDBMS allows the creation of an object called View.
An interesting fact about a View is that it is stored only as a definition. It actually does not store the data of their
own (That is why; view is called a virtual table). When a reference is made to a view, its definition is scanned, the
base table is opened and the data related to the constructed view is accessible.
A view can contain all or selected number of rows from a table.
Views allow users to do the following:
Structure data in a way that users (or groups of users) find it convenient
Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they need
and no more
Summarize data from various tables which can be used to generate reports
Creating Views: Database views are created using the CREATE VIEW statement. Views can be created from a single
table, multiple tables or another view
Syntax for Creating a View:
Output:
EMPNO ENAME
7369 Smith
7499 Allen
7521 Ward
7566 Jones
7654 Martin
7698 Blake
Syntax for Updating a View: The definition of the view created in SQL can be modified by using the following syntax:
Example: CREATE OR REPLACE VIEW emp_view AS SELECT EMPNO,ENAME, SAL FROM EMP;
EMPNO ENAME SAL
7369 Smith 800
7499 Allen 1800
7521 Ward 1800
7566 Jones 2975
7654 Martin 1800
7698 Blake 1800
3.6 Sequences
Example for Creating a Sequence: The below statement creates a database sequence named SEQ1 that starts with
100, has a step of 1 and can take maximum value as 120
Example for Using a DB Sequence: Consider a table PERSON. The following SQL statement inserts a record in it using
the above created sequence
Example for Modifying a Sequence: The below statement modifies the database sequence named SEQ1
Indexes
An Index is a database object that can be used to speed up the retrieval of rows
Indexes are logically and physically independent of the table. It means they can be created or dropped at any time
and will have no effect on the base tables or other indexes
Automatic Created Indexes: When a primary key or unique key constraint is defined in a table definition then a
unique index is created automatically
Creating Indexes Manually: User can create non-unique indexes on columns to speed up access time to rows.
Example for Creating a Single Column Index: Create index emp_ename_idx on emp (ename);
Example for Creating a Multi Column Index: Create index emp_multi_idx on emp (ename, deptno);
Finding details about created indexes: The data dictionary contains the name of index, table name and column
names. For example, in Oracle RDBMS, user_ind_columns view contains the details about user created indexes
Removing an index from the data dictionary: Indexes cannot be modified. They can be dropped as below:
Drop index emp_ename_idx;
Synonyms
SQL Integrity Constraints are used to apply business rules for the database tables
Various integrity constraints available in SQL are: Primary Key, Foreign Key, NOT NULL, Unique Key, Check
Constraints can be defined in two ways:
i) The constraints can be specified immediately after the column definition. This is called column-level
definition
ii) The constraints can be specified after all the columns are defined. This is called table-level definition
This constraint defines a column or combination of columns which uniquely identifies each row in the table
Syntax to define a primary key at column level: colname datatype (length) primary key
Method1:
primary key (colname1, colname2, ..) where colname1, colname2 are the names of the columns
which define the primary key
Method1:
This constraint identifies any column referencing the primary key in another table
It establishes a relationship between two columns in the same table or between different tables
For a column to be defined as a foreign key, it should be defined as a primary key in the table which it is
referring
Syntax to define a foreign key at column level:
Colname datatype (length) references parent_table_name (primary_key_of_parent_table)
Example to define a foreign key at column level:
Create table student
(
rollno number (2),
name varchar2(15),
courseno number(2) references course (courseid)
);
Syntax to define a foreign key at table level:
Foreign key (colname) references parent_table_name (primary_key_of_parent_table)
Example to define a foreign key at table level:
Create table student
(
rollno number (2),
name varchar2(15),
courseno number(2),
location varchar2(15),
foreign key (courseno) references course (courseid)
);
This constraint ensures all rows in the table contain a definite value for the columns which are specified as
not null (which means a null value is not allowed)
Syntax to define a Not Null constraint: colname datatype (length) NOT NULL
Example to define a Not Null constraint: To create a student table with name field mandatory, the Not Null
constraint defined would be like:
This constraint ensures that a column or a group of columns defined as a unique key have a distinct value in
all rows
Column(s) defined as unique key cannot have duplicate values
Column(s) defined as unique key can have a null value
Syntax to define a Unique key at column level: colname datatype (length) UNIQUE
Example to define a Unique key at column level:
This constraint defines a business rule on a column. All the rows must satisfy this rule
This constraint can be applied for a single column or a group of columns
Syntax to define a Check constraint at column level:
colname datatype (length) CHECK (condition)
Example to define a Check constraint at column level:
Create table student
(
Rollno number(2),
Name varchar2(15),
Gender varchar2(1) CHECK (gender in (‘M’,’F’))
);
Syntax to define a Check constraint at table level:
CHECK (condition)
Example to define a Check constraint at table level:
Create table student
(
Rollno number(2),
Name varchar2(15),
Gender varchar2(1),
CHECK (gender in (‘M’,’F’))
);
1) Group Functions:
These functions group the rows of data based on the values returned by the query
The group functions are used to calculate aggregate values like total or average, which return just one value
after processing a group of rows
Below table lists the Group functions in Oracle:
Group Function Description
MIN(X) gets the minimum value in a set of values in column X
MAX(X) gets the maximum value in a set of values in column X
SUM(X) calculates the sum of values in column X
AVG(X) calculates the average of a set of values in column X
COUNT(X) counts the number of values in column X in a specified table or view
COUNT(*) counts the number of records in a specified table or view
Single row or Scalar functions return a value for every row that is processed in a query
There are four types of single row functions. They are:
i) Numeric Functions:
These are the functions that accept numeric inputs, process them and return numeric values
Few of the numeric functions are tabulated below:
These are functions that accept character inputs, process them and can return both character as
well as numeric values
Few of the character functions are tabulated below:
These are functions that take DATE type inputs, process them and return values of DATE type
(except for the MONTHS_BETWEEN function, which returns a number)
Few of the DATE functions are tabulated below:
These are functions that help us to convert a value in one form to another form. For Example: a null
value into an actual value, or a value from one data type to another data type
Few of the conversion functions available in oracle are tabulated below: