0% found this document useful (0 votes)
113 views11 pages

Constraints: Not Null Unique Key Check Primary Key Foreign Key

Integrity constraints are used to define rules for valid data values and relationships between columns and tables. The main types of constraints are NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK. Primary keys uniquely identify each row in a table. Foreign keys reference the primary keys or unique keys of other tables to define relationships. Constraints can be defined at the column or table level when creating or altering tables. Constraints can be enabled, disabled, or dropped as needed.

Uploaded by

master_coders
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views11 pages

Constraints: Not Null Unique Key Check Primary Key Foreign Key

Integrity constraints are used to define rules for valid data values and relationships between columns and tables. The main types of constraints are NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK. Primary keys uniquely identify each row in a table. Foreign keys reference the primary keys or unique keys of other tables to define relationships. Constraints can be defined at the column or table level when creating or altering tables. Constraints can be enabled, disabled, or dropped as needed.

Uploaded by

master_coders
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

Constraints

Integrity Constraints are used to prevent the entry of invalid information into tables.

Constraints can be defined at the column or table level


Column level constraints go directly after the column definition
Table level constraints go after the last column definition.

Constraint types

Not Null
Unique Key
Check
Primary Key
Foreign Key

Primary Key
Each table can have one primary key, which uniquely identifies each row in a table.

Foreign Key
the values in the FOREIGN KEY column must refer to existing values in the other table.
A foreign key column can refer to primary key or unique key column of other tables.

Note:
You cannot delete a parent record if any existing child record is there.
If you define the FOREIGN KEY with ON DELETE CASCADE option then you can
delete the parent record and if any child record exist it will be automatically deleted.

Example

To define a foreign key constraint with ON DELETE CASCADE option

Alter table attendance add constraint empno_fk


          Foreign key (empno) references emp(empno)
              on delete cascade;               

Examples
Defining Constraints in CREATE TABLE statement.
 
create table emp (
empno number(5) constraint emppk Primary key,
ename varchar2(20) constraint namenn not null,
                   sal  number(10,2) constraint salcheck check (sal between 1000 and 20000)
             idno varchar2(20) constraint id_unique unique
);
 
create table attendance (
empno number(5) constraint empfk references emp (empno) on delete cascade,
month varchar2(10),
days number(2) constraint dayscheck check (days <= 31)
);
 
The name of the constraints are optional.
If you don’t define the names then oracle generates the names randomly like ‘SYS_C1234’
  
Another way of defining constraint in CREATE TABLE statement.
 
create table emp (
empno number(5),
ename varchar2(20) not null,
sal  number(10,2),
idno varchar2(20),

constraint emppk Primary key (empno),


constraint salcheck check (sal between 1000 and 20000),
constraint id_unique unique (idno)
);
 
create table attendance (
empno number(5),
month varchar2(10),
days number(2),

constraint empfk foreign key (empno) references emp (empno) on delete cascade,
constraint dayscheck check (days <= 31)
);

To define a primary key on the existing table


Alter table emp add constraint emppk primary key (empno);

To define a foreign key on the existing table


Alter table attendance add constraint empno_fk
     Foreign key (empno) references emp(empno);

Check Constraint
Alter table attendance add constraint dayscheck
              Check (days <= 31);

Alter table emp add constraint sal_check


                    check (sal between 1000 and 20000);

Enabling and Disabling Constraints

Syntax: ALTER TABLE <TABLE_NAME> ENABLE/DISABLE


           CONSTRAINT  <CONSTRAINT_NAME>

Dropping constraints
To drop primary key constraint from emp table.
Alter table emp drop constraint emppk;

Note: You have to first drop the foreign key and then drop the primary key.

Viewing Information about constraints


 
To see information about constraints, you can query the following data dictionary tables.
 
select * from user_constraints;
select * from user_cons_columns;

GROUP BY:
The GROUP BY clause can be used in SELECT statement by grouping up the data from multiple
records from a table (or tables), and at least one arithmetic operator should appear on
SELECT statement.

Syntax:

SELECT Column1, Column2, Aggreate function


FROM TableName
WHERE <condition>
GROUP BY Column1, Column2
HAVING Aggreate function Condition
ORDER BY Column ASC / DESC

GROUP BY StudentName

SELECT StudentName, SUM(Mark) AS 'Total for Each Student'


FROM dbo.StudentMark
GROUP BY StudentName;

HAVING: used to filter the groups

SELECT StudentName, SUM(Mark) AS 'Students Scored > 35'


FROM dbo.StudentMark
GROUP BY StudentName
HAVING SUM(Mark) > 35

SELECT StudentName, SUM(Mark) AS 'Students Scored 20 - 45'


FROM dbo.StudentMark
GROUP BY StudentName
HAVING SUM(Mark) BETWEEN 20 AND 45

SELECT StudentName, SUM(Mark) AS 'Student who scored on 3 subjects'


FROM dbo.StudentMark
GROUP BY StudentName
HAVING COUNT(*) = 3

SELECT StudentName, SubjectName, Mark FROM dbo.StudentMark


ORDER BY StudentName ASC, Mark DESC;

Operators
||   Concatenates character strings SELECT 'The Name of the
employee is: ' || ENAME FROM
EMP;

=  Equality test. SELECT ENAME "Employee" FROM


EMP WHERE SAL = 1500;

!=, ^=, <> Inequality test. SELECT ENAME FROM EMP WHERE
SAL ^= 5000;

>  Greater than test. SELECT ENAME "Employee", JOB


"Title" FROM EMP WHERE SAL >
3000;

<  Less than test. SELECT * FROM PRICE WHERE


MINPRICE < 30;

>=   Greater than or equal to test. SELECT * FROM PRICE WHERE


MINPRICE >= 20;

<=   Less than or equal to test. SELECT ENAME FROM EMP WHERE
SAL <= 1500;

IN "Equivalent to any member of" test. SELECT * FROM EMP WHERE


ENAME IN ('SMITH', 'WARD');
Equivalent to "= ANY".
ANY/ SOME Compares a value to each value in a list or SELECT * FROM DEPT WHERE LOC
returned by a query. Must be preceded by =, ! =YORK','DALLAS');
SOME ('NEW
=, >, <, <=, or >=. Evaluates to FALSE if the
query returns no rows.
NOT IN Equivalent to "!= ANY". Evaluates to SELECT * FROM DEPT WHERE LOC
NOT IN ('NEW YORK',
FALSE if any member of the set is NULL. 'DALLAS');

ALL Compares a value with every value in a list or SELECT * FROM emp WHERE sal
returned by a query. Must be preceded by =, ! >= ALL (1400, 3000);
=, >, <, <=, or >=. Evaluates to TRUE if the
query returns no rows.
[NOT] [Not] greater than or equal to x and less than SELECT ENAME, JOB FROM EMP
WHERE SAL BETWEEN 3000 AND
BETWEEN x or equal to y.
5000;
and y
EXISTS TRUE if a sub-query returns at least one row. SELECT * FROM EMP WHERE
EXISTS (SELECT ENAME FROM
EMP WHERE MGR IS NULL);

IS [NOT] Tests for nulls. This is the only operator that SELECT * FROM EMP WHERE COMM
IS NOT NULL AND SAL > 1500;
NULL should be used to test for nulls.
NOT Returns TRUE if the following condition is SELECT * FROM EMP WHERE NOT
(job IS NULL)
FALSE. Returns FALSE if it is TRUE. If it is SELECT * FROM EMP WHERE NOT
UNKNOWN, it remains UNKNOWN. (sal BETWEEN 1000 AND 2000)

AND Returns TRUE if both component conditions SELECT * FROM EMP WHERE
job='CLERK' AND deptno=10
are TRUE. Returns FALSE if either is
FALSE; otherwise returns UNKNOWN.
OR Returns TRUE if either component condition SELECT * FROM emp WHERE
is TRUE. Returns FALSE if both are FALSE. job='CLERK' OR deptno=10
Otherwise, returns UNKNOWN.
UNION Returns all distinct rows selected SELECT * FROM
by either query.
(SELECT ENAME FROM EMP WHERE
JOB = 'CLERK'

UNION

SELECT ENAME FROM EMP WHERE


JOB = 'ANALYST');

UNION ALL Returns all rows selected by either SELECT * FROM


query, including all duplicates.
(SELECT SAL FROM EMP WHERE JOB
= 'CLERK'

UNION

SELECT SAL FROM EMP WHERE JOB


= 'ANALYST');

INTERSECT and Returns all distinct rows selected SELECT * FROM orders_list1
INTERSECT ALL by both queries.
INTERSECT

SELECT * FROM orders_list2

MINUS Returns all distinct rows selected SELECT * FROM (SELECT SAL FROM
EMP WHERE JOB = 'PRESIDENT'
by the first query but not the
second.
MINUS

SELECT SAL FROM EMP WHERE JOB


= 'MANAGER');

Oracle SQL Functions

There are two types of functions in Oracle.

1) Single Row Functions:

Single row or Scalar functions return a value for every row that is processed in a query.

2) Group Functions:

These functions group the rows of data based on the values returned by the query. This is discussed in

SQL GROUP Functions. The group functions are used to calculate aggregate values like total or

average, which return just one total or one average value after processing a group of rows.
There are four types of single row functions. They are:

1) Numeric Functions:

These are functions that accept numeric input and return numeric values.

2) Character or Text Functions:

These are functions that accept character input and can return both character and number values.

3) Date Functions:
These are functions that take values that are of datatype DATE as input and return values of
datatype DATE, except for the MONTHS_BETWEEN function, which returns a number.

4) Conversion Functions:
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 datatype to another datatype
like NVL, TO_CHAR, TO_NUMBER, TO_DATE etc.

You can combine more than one function together in an expression. This is known as nesting of functions.

What is a DUAL Table in Oracle?


This is a single row and single column dummy table provided by oracle. This is used to perform
mathematical calculations without using a table.

Select * from DUAL

Output:
DUMMY
-------
X

Select 777 * 888 from Dual

Output:
777 * 888
---------
689976

1) Numeric Functions:
Numeric functions are used to perform operations on numbers. They accept numeric values as input and
return numeric values as output. Few of the Numeric functions are:

Function
Return Value
Name

ABS (x) Absolute value of the number 'x'

CEIL (x) Integer value that is Greater than or equal to the number 'x'

FLOOR (x) Integer value that is Less than or equal to the number 'x'
TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places

ROUND (x, y) Rounded off value of the number 'x' up to the number 'y' decimal places

The following examples explains the usage of the above numeric functions

Function Name Examples Return Value

ABS (1) 1
ABS (x)
ABS (-1) -1

CEIL (2.83) 3

CEIL (x) CEIL (2.49) 3

CEIL (-1.6) -1

FLOOR (2.83) 2

FLOOR (x) FLOOR (2.49) 2

FLOOR (-1.6) -2

ROUND (125.456, 1) 125.4

TRUNC (x, y) ROUND (125.456, 0) 125

ROUND (124.456, -1) 120

TRUNC (140.234, 2) 140.23

TRUNC (-54, 1) 54
ROUND (x, y)
TRUNC (5.7) 5

TRUNC (142, -1) 140

These functions can be used on database columns.

For Example:
Let's consider the product table used in sql joins.
We can use ROUND to round off the unit_price to the nearest integer,
if any product has prices in fraction.

SELECT ROUND (unit_price) FROM product;

2) Character or Text Functions:


Character or text functions are used to manipulate text strings. They accept strings or characters as input
and can return both character and number values as output.

Few of the character or text functions are as given below:

Function Name Return Value

LOWER (string_value) All the letters in 'string_value' is converted to lowercase.

UPPER (string_value) All the letters in 'string_value' is converted to uppercase.

INITCAP (string_value) All the letters in 'string_value' is converted to mixed case.

LTRIM (string_value,
All occurrences of 'trim_text' is removed from the left of 'string_value'.
trim_text)

RTRIM (string_value,
All occurrences of 'trim_text' is removed from the right of 'string_value' .
trim_text)

TRIM (trim_text FROM All occurrences of 'trim_text' from the left and right of 'string_value' ,

string_value) 'trim_text' can also be only one character long .

SUBSTR (string_value, m, Returns 'n' number of characters from 'string_value' starting from the 'm'

n) position.

LENGTH (string_value) Number of characters in 'string_value' in returned.

LPAD (string_value, n, Returns 'string_value' left-padded with 'pad_value' . The length of the whole

pad_value) string will be of 'n' characters.

RPAD (string_value, n, Returns 'string_value' right-padded with 'pad_value' . The length of the whole

pad_value) string will be of 'n' characters.

For Example, we can use the above UPPER() text function with the column value as follows.
SELECT UPPER (product_name) FROM product;
The following examples explains the usage of the above character or text functions

Function Name Examples Return Value

LOWER(string_value) LOWER('Good Morning') good morning

UPPER(string_value) UPPER('Good Morning') GOOD MORNING

INITCAP(string_value) INITCAP('GOOD MORNING') Good Morning

LTRIM(string_value, trim_text) LTRIM ('Good Morning', 'Good) Morning

RTRIM (string_value, trim_text) RTRIM ('Good Morning', ' Morning') Good

TRIM (trim_text FROM string_value) TRIM ('o' FROM 'Good Morning') Gd Mrning

SUBSTR (string_value, m, n) SUBSTR ('Good Morning', 6, 7) Morning

LENGTH (string_value) LENGTH ('Good Morning') 12

LPAD (string_value, n, pad_value) LPAD ('Good', 6, '*') **Good

RPAD (string_value, n, pad_value) RPAD ('Good', 6, '*') Good**

3) Date Functions:

These are functions that take values that are of datatype DATE as input and return values of datatypes

DATE, except for the MONTHS_BETWEEN function, which returns a number as output.

Few date functions are as given below.

Function Name Return Value

ADD_MONTHS (date, n) Returns a date value after adding 'n' months to the date 'x'.

MONTHS_BETWEEN (x1,
Returns the number of months between dates x1 and x2.
x2)
Returns the date 'x' rounded off to the nearest century, year, month, date, hour,
ROUND (x, date_format)
minute, or second as specified by the 'date_format'.

Returns the date 'x' lesser than or equal to the nearest century, year, month,
TRUNC (x, date_format)
date, hour, minute, or second as specified by the 'date_format'.

NEXT_DAY (x, week_day) Returns the next date of the 'week_day' on or after the date 'x' occurs.

It is used to determine the number of days remaining in a month from the date
LAST_DAY (x)
'x' specified.

SYSDATE Returns the systems current date and time.

NEW_TIME (x, zone1,


Returns the date and time in zone2 if date 'x' represents the time in zone1.
zone2)

The below table provides the examples for the above functions

Function Name Examples Return Value

ADD_MONTHS ( ) ADD_MONTHS ('16-Sep-81', 3) 16-Dec-81

MONTHS_BETWEEN( ) MONTHS_BETWEEN ('16-Sep-81', '16-Dec-81') 3

NEXT_DAY( ) NEXT_DAY ('01-Jun-08', 'Wednesday') 04-JUN-08

LAST_DAY( ) LAST_DAY ('01-Jun-08') 30-Jun-08

NEW_TIME( ) NEW_TIME ('01-Jun-08', 'IST', 'EST') 31-May-08

4) Conversion Functions:

These are functions that help us to convert a value in one form to another form. For Ex: a null value into an

actual value, or a value from one datatype to another datatype like NVL, TO_CHAR, TO_NUMBER,

TO_DATE.
Few of the conversion functions available in oracle are:

Function Name Return Value

Converts Numeric and Date values to a character string value. It cannot be


TO_CHAR (x [,y])
used for calculations since it is a string value.

TO_DATE (x [, Converts a valid Numeric and Character values to a Date value. Date is

date_format]) formatted to the format specified by 'date_format'.

NVL (x, y) If 'x' is NULL, replace it with 'y'. 'x' and 'y' must be of the same datatype.

DECODE (a, b, c, d, e, Checks the value of 'a', if a = b, then returns 'c'. If a = d, then returns 'e'. Else,

default_value) returns default_value.

The below table provides the examples for the above functions

Function Name Examples Return Value

TO_CHAR (3000, '$9999') $3000


TO_CHAR ()
TO_CHAR (SYSDATE, 'Day, Month YYYY') Monday, June 2008

TO_DATE () TO_DATE ('01-Jun-08') 01-Jun-08

NVL () NVL (null, 1) 1

nvl2  will return different values based on whether the input value is NULL or not.

Syntax: nvl2(input_value, return_if_not_null, return_if_null)

You might also like