DBMS_RANDOM Package - Oracle Random Number Generation
DBMS_RANDOM Package Overview
Section titled “DBMS_RANDOM Package Overview”The DBMS_RANDOM
package provides Oracle’s built-in random number and string generation capabilities. It’s essential for generating test data, creating unique identifiers, sampling data, and implementing randomization in Oracle applications.
Package Overview
Section titled “Package Overview”DBMS_RANDOM generates pseudorandom numbers using a linear congruential generator algorithm. The package is installed by default and available to all Oracle users.
Key Features
Section titled “Key Features”- Generate random numbers (integer and decimal)
- Create random strings with customizable character sets
- Produce random dates and timestamps
- Seed control for reproducible sequences
- Thread-safe operation in multi-user environments
Core Functions and Procedures
Section titled “Core Functions and Procedures”DBMS_RANDOM.VALUE
Section titled “DBMS_RANDOM.VALUE”Generates random decimal numbers between 0 and 1, or within a specified range.
-- Basic syntaxDBMS_RANDOM.VALUE RETURN NUMBERDBMS_RANDOM.VALUE(low NUMBER, high NUMBER) RETURN NUMBER
Examples:
-- Generate random number between 0 and 1SELECT DBMS_RANDOM.VALUE FROM DUAL;-- Result: 0.123456789
-- Generate random number between 1 and 100SELECT DBMS_RANDOM.VALUE(1, 100) FROM DUAL;-- Result: 45.7892341
-- Generate random integer between 1 and 10SELECT FLOOR(DBMS_RANDOM.VALUE(1, 11)) AS random_int FROM DUAL;-- Result: 7
DBMS_RANDOM.NORMAL
Section titled “DBMS_RANDOM.NORMAL”Generates normally distributed random numbers with mean 0 and standard deviation 1.
-- Generate normally distributed random numberSELECT DBMS_RANDOM.NORMAL FROM DUAL;-- Result: -0.234567891
DBMS_RANDOM.STRING
Section titled “DBMS_RANDOM.STRING”Generates random strings using specified character sets.
DBMS_RANDOM.STRING(opt CHAR, len NUMBER) RETURN VARCHAR2
Character Set Options:
'U'
- Uppercase letters (A-Z)'L'
- Lowercase letters (a-z)'A'
- Mixed case letters (A-Z, a-z)'X'
- Uppercase letters and numbers (A-Z, 0-9)'P'
- Printable characters (excluding spaces)
Examples:
-- Generate 8-character uppercase stringSELECT DBMS_RANDOM.STRING('U', 8) FROM DUAL;-- Result: HKJLMNOP
-- Generate 10-character mixed case stringSELECT DBMS_RANDOM.STRING('A', 10) FROM DUAL;-- Result: HkJlMnOpQr
-- Generate 6-character alphanumeric stringSELECT DBMS_RANDOM.STRING('X', 6) FROM DUAL;-- Result: H3K7M9
DBMS_RANDOM.SEED
Section titled “DBMS_RANDOM.SEED”Sets the seed value for reproducible random sequences.
-- Seed with specific numberEXEC DBMS_RANDOM.SEED(12345);
-- Seed with string (converted to number)EXEC DBMS_RANDOM.SEED('MYSEED');
-- Seed with current timestampEXEC DBMS_RANDOM.SEED(TO_CHAR(SYSDATE, 'DDMMYYYYHH24MISS'));
DBMS_RANDOM.INITIALIZE
Section titled “DBMS_RANDOM.INITIALIZE”Initializes the random number generator (deprecated in newer versions).
-- Initialize with seed valueEXEC DBMS_RANDOM.INITIALIZE(98765);
DBMS_RANDOM.TERMINATE
Section titled “DBMS_RANDOM.TERMINATE”Terminates the random number generator session (deprecated).
EXEC DBMS_RANDOM.TERMINATE;
Practical Examples
Section titled “Practical Examples”Generate Random Test Data
Section titled “Generate Random Test Data”-- Create sample employee dataSELECT DBMS_RANDOM.STRING('U', 3) || LPAD(FLOOR(DBMS_RANDOM.VALUE(1, 1000)), 3, '0') AS emp_id, DBMS_RANDOM.STRING('A', 8) AS first_name, DBMS_RANDOM.STRING('A', 10) AS last_name, FLOOR(DBMS_RANDOM.VALUE(25000, 100000)) AS salary, DATE '2020-01-01' + FLOOR(DBMS_RANDOM.VALUE(0, 1461)) AS hire_dateFROM DUALCONNECT BY LEVEL <= 10;
Random Sampling
Section titled “Random Sampling”-- Select 10% random sample from large tableSELECT *FROM ( SELECT *, DBMS_RANDOM.VALUE() AS rnd FROM large_table ORDER BY rnd)WHERE ROWNUM <= (SELECT COUNT(*) * 0.1 FROM large_table);
Generate Random Passwords
Section titled “Generate Random Passwords”-- Generate secure 12-character passwordSELECT DBMS_RANDOM.STRING('U', 3) || DBMS_RANDOM.STRING('L', 3) || FLOOR(DBMS_RANDOM.VALUE(100, 999)) || DBMS_RANDOM.STRING('P', 3) AS passwordFROM DUAL;
Random Date Generation
Section titled “Random Date Generation”-- Generate random dates in 2023SELECT DATE '2023-01-01' + FLOOR(DBMS_RANDOM.VALUE(0, 365)) AS random_dateFROM DUALCONNECT BY LEVEL <= 5;
Weighted Random Selection
Section titled “Weighted Random Selection”-- Weighted random selection with biasWITH weights AS ( SELECT 'A' item, 50 weight FROM DUAL UNION ALL SELECT 'B' item, 30 weight FROM DUAL UNION ALL SELECT 'C' item, 20 weight FROM DUAL),cumulative AS ( SELECT item, weight, SUM(weight) OVER (ORDER BY item) AS cum_weight, SUM(weight) OVER () AS total_weight FROM weights)SELECT itemFROM cumulativeWHERE DBMS_RANDOM.VALUE(0, total_weight) <= cum_weightAND ROWNUM = 1;
Performance Considerations
Section titled “Performance Considerations”Efficiency Tips
Section titled “Efficiency Tips”- Minimize Function Calls: Store random values in variables when used multiple times
- Batch Generation: Generate multiple random values in single query when possible
- Seeding Strategy: Use appropriate seeding for your use case
-- Efficient: Generate once, use multiple timesDECLARE v_random NUMBER := DBMS_RANDOM.VALUE(1, 100);BEGIN -- Use v_random multiple times INSERT INTO table1 VALUES (v_random, 'data1'); INSERT INTO table2 VALUES (v_random, 'data2');END;/
Memory Usage
Section titled “Memory Usage”DBMS_RANDOM has minimal memory overhead and is designed for high-performance operations.
Common Use Cases
Section titled “Common Use Cases”1. Test Data Generation
Section titled “1. Test Data Generation”Generate realistic test datasets for development and testing environments.
2. A/B Testing
Section titled “2. A/B Testing”Randomly assign users to different test groups for statistical analysis.
3. Load Balancing
Section titled “3. Load Balancing”Distribute workload randomly across multiple resources or servers.
4. Gaming Applications
Section titled “4. Gaming Applications”Implement random events, dice rolls, and probability-based mechanics.
5. Security Applications
Section titled “5. Security Applications”Generate random tokens, session IDs, and one-time passwords.
6. Statistical Sampling
Section titled “6. Statistical Sampling”Create random samples from large datasets for analysis.
Best Practices
Section titled “Best Practices”Seeding Strategy
Section titled “Seeding Strategy”-- Production: Use time-based seed for uniquenessEXEC DBMS_RANDOM.SEED(EXTRACT(SECOND FROM SYSTIMESTAMP) * 1000000);
-- Testing: Use fixed seed for reproducible resultsEXEC DBMS_RANDOM.SEED(12345);
Error Handling
Section titled “Error Handling”DECLARE v_random NUMBER;BEGIN BEGIN v_random := DBMS_RANDOM.VALUE(1, 100); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Random generation failed: ' || SQLERRM); v_random := 50; -- Default value END;END;/
Thread Safety
Section titled “Thread Safety”DBMS_RANDOM is thread-safe and can be used safely in concurrent environments without additional synchronization.
Limitations and Considerations
Section titled “Limitations and Considerations”- Pseudorandom: Not cryptographically secure; use DBMS_CRYPTO for security purposes
- Range Limitations: Maximum range depends on Oracle NUMBER precision
- Performance: While fast, excessive calls in tight loops may impact performance
- Seed Persistence: Seeds don’t persist across database restarts
Alternative Approaches
Section titled “Alternative Approaches”DBMS_CRYPTO.RANDOMBYTES
Section titled “DBMS_CRYPTO.RANDOMBYTES”For cryptographically secure random values:
SELECT DBMS_CRYPTO.RANDOMBYTES(8) FROM DUAL;
SYS_GUID()
Section titled “SYS_GUID()”For unique identifiers:
SELECT SYS_GUID() FROM DUAL;
SAMPLE Function
Section titled “SAMPLE Function”For random sampling:
SELECT * FROM large_table SAMPLE(10);
Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”Issue: Predictable sequences in concurrent sessions Solution: Use unique seeds per session
EXEC DBMS_RANDOM.SEED(USERENV('SESSIONID') + DBMS_UTILITY.GET_TIME);
Issue: Same random values across database restarts Solution: Initialize with timestamp-based seed at startup
Issue: Performance degradation with high-frequency calls Solution: Batch generate and cache random values when possible
Version Compatibility
Section titled “Version Compatibility”- Oracle 8i+: Core DBMS_RANDOM functionality
- Oracle 9i+: Enhanced string generation options
- Oracle 11g+: Improved performance and thread safety
- Oracle 12c+: Additional character set support
Related Functions
Section titled “Related Functions”DBMS_CRYPTO
- Cryptographic functionsSYS_GUID
- Unique identifier generationSAMPLE
- Table sampling
Summary
Section titled “Summary”DBMS_RANDOM is Oracle’s primary tool for generating pseudorandom values. It provides efficient, flexible random number and string generation suitable for most application needs. While not cryptographically secure, it offers excellent performance for test data generation, sampling, and general randomization requirements.
For production applications requiring cryptographic security, consider using DBMS_CRYPTO instead. Always test random generation patterns in your specific environment to ensure they meet your application’s requirements.