0% found this document useful (0 votes)
4 views

Creating Tables in SQL

Uploaded by

Thypon Live
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Creating Tables in SQL

Uploaded by

Thypon Live
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Module 2

Functions in SQL

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Single-Row Functions

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
What is a Function?

• Functions are created for manipulating the data and returning a value.
• Functions must be created before calling them. Otherwise, you will have the following error:

• Functions are formerly created codes that reside in the database. They can be called easily by typing only their
names and parameters.
• A function is a bunch of code created for reuse.
• There are two types of functions:
1. Single-Row Functions
2. Multiple-Row Functions

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Oracle Function Types

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Single-Row Functions

• The single row functions operate on single rows and return only one result per row.
• Accept one or more arguments and return one value.
• Return value for each row returned.
• Can be used alone or nested.
• A column or an expression can be used as arguments.
• The returning data type can be different than the input data types.
• Can be used in SELECT, WHERE or ORDER BY clauses.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Single-Row Functions

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Overview of Single-Row Functions

• Functions are categorized by the data types of their input parameters.


• Character Functions: Accept character values as input, and return character or
numeric values.
• Number Functions: Accept numeric values as input and return numeric values
as output.
• Date Functions: Operate on values of the DATE data type.
• Conversion Functions: Used to convert one data type to another.
• General Functions: These functions take in any data type. But, they are mainly
used to handle the NULL values.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Character Functions

• Character functions take in character data as input and return character or numeric data as output
• There are two different types of character functions:

1. Case Conversion functions: Convert characters to upper case or lower case


1. UPPER function
2. LOWER function
3. INITCAP function
2. Character Manipulation functions:
1. SUBSTR function
2. LENGTH function
3. CONCAT function
4. INSTR function
5. TRIM function
6. REPLACE function
7. LPAD I RPAD function

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Case Conversion Functions
• Case conversion functions are used to convert the characters to uppercase or lowercase characters.
LOWER Function: Converts all the input characters to lowercase characters.
UPPER Function: Converts all the input characters to uppercase characters.
INITCAP Function: Converts first letters of each word to uppercase and rest of them to lowercase.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Character Manipulation Functions

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Numeric Functions

Numeric functions accept numeric values as the input and return numeric values as the
output.
• ROUND: Takes in a number and rounds it to the specified number of decimal places.
• TRUNC: Truncates values to the specified number of decimal places.
• CEIL: Returns the smallest integer number greater than or equal to a specified number.
• FLOOR: Returns the highest integer number less than or equal to a specified number.
• MOD: Returns the remainder of division.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Nested Functions
• Functions can be nested within each other. This is called Nesting functions.
• Nested functions are evaluated starting from the innermost function and executed one by
one toward the outermost one.
• The result of the innermost function becomes the input of the outer function.
• We can use as many nested functions as we want.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Date Values & Formats in Oracle
• DATE is the main datatype used in Oracle for storing the date values.
• Oracle Database stores the date values in an internal numeric format.
• It stores a seven-byte number that contains the century, year, month, day, and hour,
minute, and second.
• There are many different date representations in Oracle like (‘DD-MON-RR' , ‘DD-MM-YY' ,
‘DD/MM/YYYY' ,etc.)

• The RR date format is a different time format element that allows us to show 20th-century
dates in the 21st century using only 2 digits.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
DATE Data Types in Oracle

• DATE: The standard data type that stores date values in Oracle.
• TIMESTAMP: This data type stores year, month, day, hour, minute, second as well as
fractional seconds.
• TIMESTAMP WITH TIME ZONE: This data type is the same as TIMESTAMP, but it stores
the timezone along with it.
• TIMESTAMPT WITH LOCAL TIME ZONE: This data type is similar to TIMESTAMP WITH
TIME ZONE, but the stored timezone is the database's timezone.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Oracle Date Functions

• SYSDATE: returns the current date and time of the OS where the Oracle Database is installed.
• CURRENT DATE: returns the current date and time of the place where the user's session is logged
in from.
• SESSIONTIMEZONE: returns time zone of the user's session.
• SYSTIMESTAMP: returns the date and time of the database.
• CURRENT TIMESTAMP: returns current date and time from user's session.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Arithmetic Operations with Dates

• We can add or subtract a number from a date, and the result of this operation will also be a date.
• Subtracting two dates returns the number of days between these dates.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Date Manipulation Functions

• Date functions operate on dates and return dates, numbers or texts.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Conversion Functions

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Oracle Conversion Functions

• Oracle Conversion Functions convert one data type into another.

1. Implicit Conversion: Oracle server automatically converts some data type to the required
one.
• Although implicit conversion converts some data types automatically, it is recommended
to use the explicit conversion functions to ensure the reliability of SQL statements.
2. Explicit Conversion: Explicit conversions are done using the conversion functions explicitly.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Implicit Data Type Conversion

• A VARCHAR2 or CHAR value is converted to a NUMBER or a DATE by the Oracle server


automatically.
• Similarly, a NUMBER or a DATE value is automatically converted to character data by the
Oracle server.
• The implicit conversions are performed only if the characters match with a valid number or
date.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Explicit Data Type Conversion

• Used for converting data type of a value to another data type explicitly.
• There are 3 functions for explicit data type conversion which are:
1. TO_CHAR ()
2. TO_NUMBER ()
3. TO_DATE ()

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
TO_CHAR Function
• Converts the NUMBER or DATE to the VARCHAR2 data type in the specified format
model.
• The syntax of the TO CHAR function is:

• date I number: This is the value to be converted into the VARCHAR2 type. It can be a date or a
number.
• format_model: The input value is converted to the VARCHAR2 data type in the specified format
model.
• nls_parameter: Specifies the language for the names and abbreviations of the days and months
(E.g., Monday - Mon, January - Jan, etc.)
• The TO CHAR function is case-sensitive.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
DATE Format Models

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
NUMBER Format Models

• Number format models are used with the TO CHAR function to display the
numeric values in different formats.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
TO_NUMBER Function

• The TO NUMBER function is used to convert a text to a number.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
TO_DATE Function

• Converts the characters to a DATE data type in the specified format model.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
NVL Function
• The NVL function allows us to replace a null value with a meaningful alternative.

• If expressionl is null, then NVL() function returns expression2.


• Data types can be characters, numbers or dates.
• Data types must match with each other (number-number, date-date, character-
character
• The NVL function is extremelv useful in arithmetic ooerations to avoid calculation
errors.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
NVL2 Function
• The NVL2 function allows us replace a value when a null value is encountered as
well as when a non-null value is encountered.

• If the Expression1 is not null then, it returns the Expression2. If the Expression1 is
NULL, then, the Expression3 is returned.
• And the Expression1 does not have to be the same data type in Expression2 and
Expression3. But, the Expression2 and Expression3 must be in the same data type.
• Data types can be the characters, numbers or dates.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
NULLIF Function

• Compares Expression1 and Expression2. If they are equal, returns NULL. But, if they are not equal,
returns Expression1.
• The Expression1 and Expression2 must be in same data type.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
COALESCE Function

• The COALESCE function accepts a list of arguments and returns the first one that
evaluates to a non-null value.

• It accepts at least two or more parameters.


• If all the specified expressions are NULL, then the function returns NULL.
• All of the expressions must be in the same data type.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Conditional Expressions

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
CASE ... WHEN Expression

• Performs an IF-THEN-ELSE check within an SQL statement.

• Expression and comparison expressions must be in the same data type.


• Can be used in both SELECT and WHERE clauses.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
CASE ... WHEN Expression (continued)

• There are two ways of using the CASE expressions which are Simple Case Expression and
Searched Case Expression.

Simple CASE Expression Searched CASE Expression

• The expression is stated at the beginning, • The expressions are used within each
and the possible results are checked in the condition without mentioning it at the start
condition parameters. of the CASE expression.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
CASE Expression in SELECT Statement

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
CASE Expression in WHERE Clause

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
DECODE Function

• The DECODE is a function that is specific to Oracle, easy to use, and an alternative to the CASE
expressions.
• It is used to provide an if-then-else logic in SQL.
• The CASE is an expression whereas DECODE is a function.

• All the search expressions must be in the same data type.


• All the result expressions must be in the same data type.
• But, the search and result expressions don't have to be in the same data type.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
DECODE Function

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Reporting Aggregated Data Using
the Group Functions

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Oracle Function Types

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Oracle Group Functions

• Group functions operate on multiple rows and return one result for each group.
• Group functions are usually used after the SELECT keyword.
• Multiple group functions can be used in a single SELECT statement.
• Group functions ignore the NULL values! But, you can use the NVL, NVL2, COALESCE, DECODE functions
or CASE expressions to handle the NULL values.
• The DISTINCT and ALL(default) keywords are used with the group function to consider duplicate values.
• CHAR, VARCHAR2, NUMBER or DATE data types can be used.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Oracle Group Functions

• AVG: Returns the average value.


• COUNT: Returns the number of rows returned by a query.
• MAX: Returns the maximum value of the expression or a column.
• MIN: Returns the minimum value of the expression or a column.
• SUM: Returns the sum of the expression or column values.
• LISTAGG: Transforms and orders data from multiple rows into a single list of
values separated by a specified delimiter.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
AVG Function
• The AVG function is used for getting the average value of the columns or expressions.

• It is exclusively used with numeric data.


• The DISTINCT, ALL keywords can be used to handle duplicate values.
• We can use the NVL, NVL2, COALESCE, CASE or DECODE functions to handle the NULL
values.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
COUNT Function

• Returns the number of rows returned by a query.

• You can use the DISTINCT keyword to count the distinct values of the expression, or ALL
keyword to count all rows.
• '*' represents all rows including the NULL values.
• If a column name is used with the Count function, this time, the NULL values are ignored.
• We can use the NVL, NVL2, COALESCE, CASE or DECODE functions to handle the NULL values.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
MAX Function

• The MAX function returns the maximum value of an expression or column.


• It is used with numeric, character or date data types.
• Using the DISTINCT or ALL keywords with the MAX function is useless.
• The null-related functions can be used with the MAX function to handle
the NULL values.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
MIN Function

• Used for getting the minimum value of the expression or column.

• Used with numeric, character and date data types.


• Using the DISTINCT or ALL keywords with the MIN function is useless.
• The NVL, NVL2, COALESCE, CASE or DECODE functions can be used to
handle the NULL values.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
UNIQUE Constraint

• A UNIQUE constraint ensures the uniqueness of a column or a set of columns which


means no duplicate values will be inserted.
• A UNIQUE column or a set of columns where the combination must be unique can have
multiple null values, unless you also define NOT NULL constraints for these columns.
• UNIQUE constraints based on multiple columns are called Composite Unique Keys.
• A composite unique constraint can contain a maximum of 32 columns.
• UNIQUE constraints can be defined at the column-level or table-level.
• Composite Unique Keys can only be created at the table-level.
• The Oracle Server creates a unique index implicitly on unique key creation.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
UNIQUE Constraint

• Let's create some unique constraints in different ways.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
PRIMARY KEY Constraint

• A PRIMARY KEY is a column or a combination of columns in a table that uniquely


identifies each row in a table.
• A PRIMARY KEY constraint is the combination of a NOT NULL and a UNIQUE constraint.
• There can only be one primary key on a table.
• We can think of a primary key as the unique ID of each row in a table.
• The Oracle Server creates a UNIQUE index when creating a primary key.
• The NOT NULL constraint is automatically created on the related column(s) when creating
a primary key.
• There are 2 types of primary keys: Simple Primary Key(single-column) and Composite
Primary Key(multiple columns).

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
FOREIGN KEY Constraint
• A foreign key is a column or combination of columns used to enforce a relationship between a parent
table and a child table.
• The relationship is established between the parent table's primary/unique key and a column or set of
columns in the child table.
• The Foreign Key constraint is also known as the Referential Integrity constraint.
• A referenced record must exist in the parent table before you can insert a related record into the child
table.
• The Foreign Key constraints can be defined at the column or table level.
• There are 2 types of foreign key constraints which are Simple and Composite Foreign Key constraints.
• Composite Foreign Keys have to be created at the table-level.
• The keyword REFERENCES is used to specify the table name and column name to be referenced in the
parent table.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
'ON DELETE CASCADE" I "ON DELETE SET NULL“ Options

• The ON DELETE CASCADE clause deletes dependent rows in the child table when a related
row in the parent table is deleted.
• The ON DELETE SET NULL clause updates dependent rows in the child table to NULL when a
related row in the parent table is deleted.

• ON DELETE CASCADE
• ON DELETE SET NULL

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
CHECK Constraint

• A CHECK constraint ensures a column or a group of columns meets a specific condition.


• We can use check constraints in arithmetic operations or conditional operations.
• We cannot create check constraints referencing another table.
• A CHECK constraint can be created at the column-level or table-level.
• A table, even a single column, can have more than one check constraint on it.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Adding Constraints via ALTER TABLE
• To add dro enable or disable a constraint we use ALTER TABLE statements.

• To add a NOT NULL CONSTRAINT, we use the ALTER TABLE MODIFY COLUMN clause.
• The table must be empty or all the values of the NOT NULL column must have a value.
• We cannot modify a constraint's structure. To do that we need to drop and re-create the constraint.
• Specifying a constraint name is optional.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Dropping (Removing) Constraints

• We use the ALTER TABLE statement to remove a constraint.

• While dropping a PRIMARY KEY constraint, we can use the CASCADE option to drop all the associated
FOREIGN KEY constraints.

• We can use the ONLINE keyword to allow DML operations while dropping constraints.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Cascading Constraints

• When we drop a column, the NOT NULL, PRIMARY KEY and UNIQUE constraints are dropped.
• If a column is used by a foreign key constraint on another table, then, we cannot drop this column
directly. The Oracle Server will return an error.
• If we use the CASCADE CONSTRAINTS clause while dropping a column, all the constraints referring to
that column's PRIMARY and UNIQUE keys are dropped.

• If there is a multi-column constraint, we need to use the CASCADE CONSTRAINTS clause to drop this
column. Otherwise, we will get an error.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Renaming Constraints

• Existing constraints can be renamed.


• The ALTER TABLE ... RENAME CONSTRAINT statement is used to rename an existing constraint of a table.
• While renaming an existing constraint, the new name must not conflict with any of the existing objects in
your schema.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Disabling Constraints

• We use ALTER TABLE statements to disable and enable constraints.


• A constraint that is disabled does not enforce its restriction on the DML operation until it is re-enabled.
• We cannot directly disable a constraint if there is one or more foreign keys referencing this constraint.
• We can use the CASCADE option to disable a constraint and all the dependent constraints.
• When we disable a unique or a primary key constraint, the Oracle Server will remove the unique indexes.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Enabling Constraints
• Disabled constraints can be enabled using the ENABLE CONSTRAINT keywords.
• Even if we enable a disabled constraint, referencing foreign keys disabled with the CASCADE option
will remain disabled.
• Disabled foreign keys must be explicitly enabled because there is no ENABLE-CASCADE option.
• When we enable a unique or a primary key constraint, a unique index is automatically created by the
Oracle Server.
• To enable a constraint, all the data in the column or table must satisfy the constraint rules.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Status of Constraints

• The ENABLE keyword ensures that all existing and new data must meet the constraint conditions.
• The DISABLE keyword allows us to enter new values whether they meet the constraint conditions or not.
• VALIDATE or NOVALIDATE can also be used with ENABLE and DISABLE for configuring existing or future data validation.
• The VALIDATE keyword ensures that the existing data must conform to the constraint conditions.
• The NOVALIDATE keyword is used to suspend the checking of existing rows for constraint violations.
• A constraint can have four states below:
1. ENABLE VALIDATE: This is the default for the ENABLE clause. All the existing rows are checked for whether they
conform to the constraint rules, plus, all future rows that will be added or modified will be checked while making
inserts or updates.
2. ENABLE NOVALIDATE: The existing rows will not be checked. Only the new rows will be checked.
3. DISABLE VALIDATE: The constraint is disabled, but it remains valid. No DML operations are allowed on the table
because the future changes will not be validated.
4. DISABLE NOVALIDATE: This is the default for the DISABLE clause. No checks are performed on existing and future
data.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Deferring Constraints

• Constraints can have 2 deferring states which are DEFERRABLE and NOT DEFERRABLE.
1. DEFERRABLE: Allows us the option of postponing enforcement of constraints to the end of a
transaction. A deferrable constraint can be created in one of two modes:
a) INITIALLY IMMEDIATE (DEFAULT): Specifies that the constraint are checked for conformance
at the end of each queryexecution.
b) INITIALLY DEFERRED: Postpones constraint enforcement until the end of the transaction
(commit).
2. NOT DEFERRABLE (DEFAULT): Indicates the enforcement of the constraint must always be done
immediately as each statement is executed.

• If we want to alter a constraint or all the constraints in a session to DEFERRED, he NOT DEFERRABLE
constraints will not change to DEFERRED.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Deferring Constraints

• A table can have multiple constraints with different deferring options.


• Any integrity constraint (PRIMARY KEYS, FOREIGN KEYS and CHECK constraints) can have any
deferring status.

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program
Ready for Next Step?

© 2024. “Gi Academy”- Data Science Course www.giacademy.az


Program

You might also like