Sub topic 2
Choosing scalar data types
This chapter assumes you can write basic SQL and run anonymous blocks in SQL*Plus, SQL Developer, or SQLcl. You should also know Oracle types such as NUMBER, VARCHAR2, and DATE.
Choosing scalar data types
A scalar type holds one value, such as a number, a string, or a date. Pick the type that matches the data:
NUMBER(p,s)stores exact numbers.NUMBER(10,2)allows up to 10 digits, with 2 after the decimal point. Use it for money.VARCHAR2(n)stores text up tonbytes.DATEstores a date and time.PLS_INTEGERstores whole numbers and is faster thanNUMBERfor loop counters and other integer work.BOOLEANholds TRUE, FALSE, or NULL. It exists only in PL/SQL, not as a table column type.
A value that does not fit the declared size raises an error at run time, so size the variable to the data it must hold.
Constants, defaults, and NOT NULL
Add CONSTANT to freeze a value. A constant must have an initial value, and you cannot change it later.
A NOT NULL variable must also have an initial value. Without one, the block fails to compile with PLS-00218.
SET SERVEROUTPUT ON
DECLARE
c_tax_rate CONSTANT NUMBER(4,3) := 0.075;
v_price NUMBER(10,2) NOT NULL := 100;
v_total NUMBER(10,2);
BEGIN
v_total := v_price * (1 + c_tax_rate);
DBMS_OUTPUT.PUT_LINE('Total: ' || v_total);
END;
/Assigning values to variables
The := operator assigns a value to a variable. Use = only in comparisons. You can also load a variable from a query with SELECT ... INTO, which fills the variable from one row.
Nested blocks, scope, and shadowing
A block can contain other blocks. A variable is visible in its own block and in the blocks nested inside it. If an inner block declares a variable with the same name as an outer one, the inner name hides the outer one. This is called shadowing.
SET SERVEROUTPUT ON
<<outer_blk>>
DECLARE
v_level VARCHAR2(10) := 'outer';
BEGIN
DECLARE
v_level VARCHAR2(10) := 'inner';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_level);
DBMS_OUTPUT.PUT_LINE(outer_blk.v_level);
END;
DBMS_OUTPUT.PUT_LINE(v_level);
END;
/The output is inner, outer, outer. The label outer_blk lets the inner block reach the shadowed variable.
::: callout note Shadowing hides bugs. Give variables distinct names, such as a v_ prefix for variables and c_ for constants, to avoid surprises. :::
Exercise
The block declares v_total as NUMBER(10,2) and computes 100 * 1.075. Does the output show 107.5 or 107.50, and why?
Show answer
It shows 107.5. The NUMBER(10,2) type fixes precision and scale, but DBMSOUTPUT.PUTLINE converts the number to text without trailing zeros.