Oracle Database@Google Cloud (ADB-S): Find Supplier Invoice Discrepancies with Select AI and Gemini
Share on LinkedIn ↗A finance analyst receives an invoice for 100 laptops at $800 each. The purchase order approved 100 laptops, but the receiving team has recorded only 90. Before approving payment, the analyst needs to understand the difference and find similar exceptions across other invoices.
The relevant information already exists in purchase orders, receiving records, and invoice tables. The challenge is bringing it together quickly enough for a business user to investigate.
In Part 1, we provisioned Oracle Autonomous Database Serverless on Google Cloud and connected through SQL Developer. In Part 2, we made the Terraform configuration reusable and introduced GitHub Actions. Here, we will use that database to answer finance questions in everyday English with Oracle Select AI and a Google Gemini model.
1. Understand the business example
Our synthetic dataset contains two suppliers and four invoices. All amounts are USD, before tax.
| Invoice | Item | Ordered | Received | Invoiced | PO unit price | Invoice unit price | Review finding |
|---|---|---|---|---|---|---|---|
| INV-1001 | Laptops | 100 | 90 | 100 | $800 | $800 | 10 invoiced units beyond receipts |
| INV-1002 | Monitors | 20 | 20 | 20 | $250 | $275 | $500 price variance |
| INV-1003 | Office chairs | 10 | 10 | 10 | $120 | $120 | Matching quantities and price |
| INV-1004 | Consulting service | No linked PO | — | 1 | — | $500 | Missing purchase-order link |
Finance can ask which purchase-order lines have more units invoiced than received, which have a positive price variance, and which invoice lines have no linked purchase order. The results identify records to review. Finance considers delivery timing, agreed payment terms, and applicable policies before deciding what to do.
2. Understand the request flow
- The analyst enters an English question in SQL Developer.
- Oracle Select AI uses the configured profile and permitted object metadata to ask Gemini for SQL.
- We display the generated SQL with
SHOWSQLand check its meaning. - Oracle executes a query through
RUNSQLusing the connected database user's privileges. - We compare the answer with a conventional SQL query over the same records.
Select AI, provider, and model are different choices
Oracle Select AI is a feature of the Autonomous database. It uses an AI profile to connect to a supported model service and turn natural-language questions into SQL or text responses.
The provider identifies the service that receives the request. The model identifies the LLM used by that service. Select AI supports multiple providers; using an Oracle database does not automatically select OCI Generative AI.
For Gemini, the examples discussed here use these different connections:
| Connection | Select AI provider | Authentication in the documented setup |
|---|---|---|
| Google AI Studio / Gemini Developer API | google |
Google API key |
| Google Cloud model platform | vertexai in our tested profile |
Google OAuth 2.0 credentials and project IAM permissions |
| A Google Gemini model offered through OCI Generative AI | oci |
OCI authentication |
The first two rows are the two Google integration options. The third routes requests through OCI Generative AI. Oracle provides separate provider examples and Google authentication instructions.
The configuration used in this walkthrough
We use Oracle Database@Google Cloud with Gemini accessed directly through Google Cloud's model service. Google's current platform name is Gemini Enterprise Agent Platform, the evolution of Vertex AI. Our tested AI profile uses:
| Setting | Value |
|---|---|
| Select AI provider | vertexai |
| Authentication | Google OAuth 2.0, stored in Oracle as VERTEX_OAUTH2_CRED |
| Model | gemini-3.5-flash-lite |
| Endpoint location | global |
| AI profile | GCP_GEMINI_FINANCE |
The request travels from SQL Developer → Oracle Select AI → Google Cloud Gemini → Oracle. Google Cloud handles model access, IAM permissions, quotas, and model usage billing. Oracle stores the invoice records and executes the SQL calculations.
The database's hosting location and the model-provider choice are separate. We selected the Google Cloud connection for this example; an alternative integration needs its corresponding profile settings, credentials, and network access.
We will start from structured invoice records loaded with SQL. Extracting fields from invoice PDFs is a separate document-processing step that can be added in a later article.
3. Prepare the existing environment
Reuse the Autonomous 26ai database, private client VM, and wallet connection from Part 1.
- Select your Google Cloud project and start the VM and database if stopped. Wait for Running and Available status.
- Open the existing PuTTY/IAP tunnel and keep it connected.
- In SQL Developer, connect as ADMIN using the saved wallet connection (
ADBS-26aiin this example). We will createSAI_DEMOin Step 6.
Open a SQL Worksheet for that connection, paste the following statements, and choose Run Script (F5). All three checks appear in Script Output.
SELECT USER, SYS_CONTEXT('USERENV', 'DB_NAME') AS database_name FROM dual;
SELECT banner_full FROM v$version;
SELECT owner, object_name, status FROM all_objects
WHERE object_name = 'DBMS_CLOUD_AI' AND object_type = 'PACKAGE';
Read the results as follows:
| Query | Result to check | Purpose |
|---|---|---|
| Connected user and database | ADMIN and your database name |
Confirms that the worksheet is connected to the intended database as its administrator |
| Database version | The Oracle release and version banner | Identifies the database release used for the examples |
| Select AI package | A DBMS_CLOUD_AI package row with STATUS equal to VALID |
Checks that the package is present and valid before setting up Select AI |
The screenshot below shows Oracle AI Database 26ai, version 23.26.4.1.0, and the DBMS_CLOUD_AI package owned by C##CLOUD$SERVICE. Your database name and version may differ. Check the STATUS column in your own output for package validity.
A successful query confirms that SQL Developer can reach the database through the existing connection. If you receive a network-adapter connection error, check that the database is available, the client VM is running, and the forwarding session remains open.

4. Enable Google model access
Select the project and enable the model API
Open PowerShell on the workstation where you installed Google Cloud CLI. Replace YOUR_PROJECT_ID with your own project ID:
gcloud config set project YOUR_PROJECT_ID
gcloud auth list
gcloud services enable aiplatform.googleapis.com --project=YOUR_PROJECT_ID
The first command selects the project used by subsequent CLI commands. The second lists the accounts signed in to Google Cloud CLI and marks its active account. The third enables the model service in the selected project; an administrator needs permission to enable services.
To check the result visually, open Google Cloud Console → APIs & Services → Enabled APIs & services, then open the service whose name is aiplatform.googleapis.com. In this environment the display name is Agent Platform API. Confirm Status: Enabled.

The API details page shows the enabled model service. Project, account, billing, and credential-label details have been blurred.
Check the identity that will call Gemini
Open IAM & Admin → IAM, select View by principals, and filter for the Google account you intend to use for model requests. Review its roles in the selected project with your administrator.
The model-calling identity needs permission to invoke the model and consume services in the project. A relevant predefined role is roles/aiplatform.user, currently listed as Agent Platform User in Google's role reference and commonly known as Vertex AI User. Follow your organization's approved IAM design. See Google's model-platform roles and permissions.

The Terraform service account provisions infrastructure. The Google identity used by the Select AI credential calls Gemini. Choose permissions for each purpose separately.
Sign in for Application Default Credentials
The CLI account listing and Application Default Credentials (ADC) are separate credential configurations. To create the local ADC file used by this walkthrough, run:
gcloud auth application-default login
Complete the Google sign-in in your browser with the intended model-calling account. Check the account displayed on the authorization screen, review the requested access, and complete the sign-in. Return to PowerShell and look for the confirmation that credentials were saved.
This command stores a local credential for applications. It does not grant IAM permissions to the account; those permissions come from the project's IAM configuration. Google documents this ADC sign-in flow.
Locate the ADC file without displaying its contents
On Windows, the standard location is %APPDATA%\gcloud\application_default_credentials.json. Open File Explorer, enter %APPDATA%\gcloud in the address bar, and locate the file. Windows may hide the .json extension, displaying the name as application_default_credentials with type JSON Source File.

File Explorer shows the ADC file in the gcloud folder. Its contents remain closed, and the Windows username has been blurred.
You can also check that the file exists without printing its contents:
Test-Path "$env:APPDATA\gcloud\application_default_credentials.json"
A result of True confirms the file exists. The model request in Step 5 checks whether the credential can access the selected model. Google describes the Windows location in How Application Default Credentials works.
For the user ADC flow documented by Oracle's Select AI vertexai integration, the credential contains the OAuth client ID, client secret, and refresh token used during setup. Keep those values private. Step 9 stores them in the database credential without including them in the blog or SQL history.
5. Check the selected model
Use a currently available Gemini model that supports Google's generateContent API. The scripts make the model selectable. This walkthrough uses gemini-3.5-flash-lite with the global endpoint. Run the following check to confirm model access in your project.
From the project directory, run:
python .\select-ai-gemini\preflight_vertex.py `
--project YOUR_PROJECT_ID `
--region global `
--model gemini-3.5-flash-lite
The helper refreshes the local OAuth credential in memory, makes a small model request, and prints a status and response. It never prints tokens. A successful response contains GCP_ORACLE_DEMO_READY. This checks Google-side model access; the later database call checks the complete integration.
The model check returned the following fields in this walkthrough:
{
"status": "success",
"model": "gemini-3.5-flash-lite",
"region": "global",
"response": "GCP_ORACLE_DEMO_READY"
}

The success status and GCP_ORACLE_DEMO_READY response confirm that the local credential can call the selected model. The model and region fields identify the configuration checked. Continue with the database user and AI profile setup to use this model from Oracle.
The global endpoint can process requests outside the database region. Choose the endpoint and model according to your organization's location requirements. A regional configuration also needs an ACL for that region's API hostname.
6. Create the demonstration database user
Use a dedicated SAI_DEMO user for the synthetic records. In the ADMIN worksheet, run 00-admin.sql from the accompanying scripts in script mode. It prompts privately for a new password, sets a small tablespace quota, and grants the package and network privileges needed for this exercise.
The script grants outbound HTTP access only to aiplatform.googleapis.com and oauth2.googleapis.com. Database ACL permission and a working outbound network path are both required. The desktop-to-database tunnel provides inbound client connectivity; it does not provide the database's outbound Google API connectivity.
Run the following commands as ADMIN using Run Script (F5). SQL Developer prompts for the new database password; enter it privately. Use your own password rather than placing one in the script.
SET VERIFY OFF
ACCEPT demo_password CHAR PROMPT 'New SAI_DEMO password: ' HIDE
CREATE USER sai_demo IDENTIFIED BY "&demo_password";
UNDEFINE demo_password
GRANT CREATE SESSION, CREATE TABLE, CREATE VIEW TO sai_demo;
ALTER USER sai_demo QUOTA 5M ON DATA;
GRANT EXECUTE ON DBMS_CLOUD TO sai_demo;
GRANT EXECUTE ON DBMS_CLOUD_AI TO sai_demo;
BEGIN
DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(
host => 'aiplatform.googleapis.com',
ace => xs$ace_type(privilege_list => xs$name_list('http'),
principal_name => 'SAI_DEMO', principal_type => xs_acl.ptype_db));
DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(
host => 'oauth2.googleapis.com',
ace => xs$ace_type(privilege_list => xs$name_list('http'),
principal_name => 'SAI_DEMO', principal_type => xs_acl.ptype_db));
END;
/
The script creates a new user and stops on errors. If that user already exists, inspect its purpose and privileges before reusing it. Keep password prompts and credentials outside screenshots.
In SQL Developer, click the green + in the Connections panel. Enter these values:
| Field | Value |
|---|---|
| Name | ADBS-26ai-SAI-DEMO |
| Database Type | Oracle |
| Authentication Type | Default |
| Username | SAI_DEMO |
| Password | The password supplied when creating SAI_DEMO |
| Role | default |
| Connection Type | Cloud Wallet |
| Configuration File | Your existing downloaded wallet ZIP |
| Service | adbs26ai_low, or the corresponding low service in your wallet |
Keep the existing tunnel open. Click Test, confirm Status: Success, click Save, and then Connect. Saving the password is optional and should follow your workstation policy.

Open the new connection's worksheet and check:
SELECT USER FROM dual;
The result identifies the connected user as SAI_DEMO. The screenshot below also shows the sample record counts after loading the data in the next step: two suppliers, three purchase-order lines, four receipt records, and four invoices.

7. Create purchase orders, receipts, and invoices
Run 10-invoice-data.sql in the SAI_DEMO worksheet using Run Script (F5). The complete script follows.
-- Connect as SAI_DEMO. Synthetic USD data. No existing objects are dropped.
WHENEVER SQLERROR EXIT SQL.SQLCODE
CREATE TABLE suppliers (
supplier_id NUMBER PRIMARY KEY, supplier_name VARCHAR2(100) NOT NULL);
CREATE TABLE po_lines (
po_line_id NUMBER PRIMARY KEY, po_number VARCHAR2(30) NOT NULL,
supplier_id NUMBER NOT NULL REFERENCES suppliers(supplier_id),
item_description VARCHAR2(100) NOT NULL,
ordered_qty NUMBER NOT NULL CHECK (ordered_qty > 0),
po_unit_price NUMBER(12,2) NOT NULL CHECK (po_unit_price >= 0));
CREATE TABLE goods_receipts (
receipt_id NUMBER PRIMARY KEY, po_line_id NUMBER NOT NULL REFERENCES po_lines(po_line_id),
received_qty NUMBER NOT NULL CHECK (received_qty > 0), receipt_date DATE NOT NULL);
CREATE TABLE invoices (
invoice_id NUMBER PRIMARY KEY, invoice_number VARCHAR2(30) NOT NULL,
supplier_id NUMBER NOT NULL REFERENCES suppliers(supplier_id), invoice_date DATE NOT NULL,
CONSTRAINT uq_supplier_invoice UNIQUE (supplier_id, invoice_number));
CREATE TABLE invoice_lines (
invoice_line_id NUMBER PRIMARY KEY, invoice_id NUMBER NOT NULL REFERENCES invoices(invoice_id),
po_line_id NUMBER REFERENCES po_lines(po_line_id),
item_description VARCHAR2(100) NOT NULL,
invoiced_qty NUMBER NOT NULL CHECK (invoiced_qty > 0),
invoice_unit_price NUMBER(12,2) NOT NULL CHECK (invoice_unit_price >= 0));
INSERT ALL
INTO suppliers VALUES (1, 'Northstar Technology')
INTO suppliers VALUES (2, 'Evergreen Office Supplies')
SELECT 1 FROM dual;
INSERT ALL
INTO po_lines VALUES (101, 'PO-1001', 1, 'Laptop', 100, 800)
INTO po_lines VALUES (102, 'PO-1002', 1, 'Monitor', 20, 250)
INTO po_lines VALUES (103, 'PO-1003', 2, 'Office chair', 10, 120)
SELECT 1 FROM dual;
INSERT ALL
INTO goods_receipts VALUES (1, 101, 50, DATE '2026-10-10')
INTO goods_receipts VALUES (2, 101, 40, DATE '2026-10-12')
INTO goods_receipts VALUES (3, 102, 20, DATE '2026-10-13')
INTO goods_receipts VALUES (4, 103, 10, DATE '2026-10-14')
SELECT 1 FROM dual;
INSERT ALL
INTO invoices VALUES (1, 'INV-1001', 1, DATE '2026-10-15')
INTO invoices VALUES (2, 'INV-1002', 1, DATE '2026-10-16')
INTO invoices VALUES (3, 'INV-1003', 2, DATE '2026-10-17')
INTO invoices VALUES (4, 'INV-1004', 2, DATE '2026-10-18')
SELECT 1 FROM dual;
INSERT ALL
INTO invoice_lines VALUES (1, 1, 101, 'Laptop', 100, 800)
INTO invoice_lines VALUES (2, 2, 102, 'Monitor', 20, 275)
INTO invoice_lines VALUES (3, 3, 103, 'Office chair', 10, 120)
INTO invoice_lines VALUES (4, 4, NULL, 'Consulting service', 1, 500)
SELECT 1 FROM dual;
COMMIT;
-- Aggregate each many-row source BEFORE joining; two laptop receipts must not
-- duplicate invoice quantities or amounts. Balances are cumulative, not allocations
-- of individual receipt rows to individual invoices.
CREATE VIEW invoice_reconciliation AS
WITH receipts AS (
SELECT po_line_id, SUM(received_qty) received_qty FROM goods_receipts GROUP BY po_line_id
), billed AS (
SELECT l.po_line_id, SUM(l.invoiced_qty) invoiced_qty,
SUM(l.invoiced_qty*l.invoice_unit_price) invoice_amount,
SUM(CASE WHEN i.supplier_id <> p.supplier_id THEN 1 ELSE 0 END) supplier_mismatch_count
FROM invoice_lines l JOIN invoices i ON i.invoice_id=l.invoice_id
JOIN po_lines p ON p.po_line_id=l.po_line_id GROUP BY l.po_line_id
)
SELECT p.po_line_id, p.po_number, s.supplier_name, p.item_description,
p.ordered_qty, NVL(r.received_qty,0) received_qty, b.invoiced_qty,
p.po_unit_price, b.invoice_amount,
GREATEST(b.invoiced_qty-NVL(r.received_qty,0),0) unreceived_invoiced_qty,
GREATEST(b.invoiced_qty-NVL(r.received_qty,0),0)*p.po_unit_price unreceived_value_at_po_price,
b.invoice_amount-b.invoiced_qty*p.po_unit_price price_variance_amount,
b.supplier_mismatch_count
FROM po_lines p JOIN suppliers s ON s.supplier_id=p.supplier_id
JOIN billed b ON b.po_line_id=p.po_line_id
LEFT JOIN receipts r ON r.po_line_id=p.po_line_id;
CREATE VIEW invoices_without_po AS
SELECT i.invoice_number, s.supplier_name, l.item_description,
l.invoiced_qty*l.invoice_unit_price invoice_amount
FROM invoices i JOIN suppliers s ON s.supplier_id=i.supplier_id
JOIN invoice_lines l ON l.invoice_id=i.invoice_id WHERE l.po_line_id IS NULL;
COMMENT ON TABLE invoice_reconciliation IS
'Cumulative USD invoice and receipt totals per purchase order line. No taxes, returns or credits. Positive price variance means billed amount exceeds billed quantity times PO unit price.';
COMMENT ON COLUMN invoice_reconciliation.unreceived_value_at_po_price IS
'Review amount in USD: cumulative invoiced units beyond cumulative received units valued at PO unit price. This is not a payment hold decision.';
COMMENT ON TABLE invoices_without_po IS
'Invoice lines without a linked purchase order line. These require finance review; a missing link does not establish policy violation.';
SELECT * FROM invoice_reconciliation ORDER BY po_line_id;
SELECT * FROM invoices_without_po;
The laptop deliveries are deliberately split into 50 and 40 units. The view aggregates receipt rows and invoice lines separately before joining them, keeping the laptop invoice at 100 units and $80,000.
The reconciliation view has one row per purchase-order line and uses cumulative quantities across linked invoices and receipts. It does not assign individual deliveries to particular invoices. The second view identifies invoice lines without a purchase-order link. The AI profile will expose these two business views.
The reconciliation query brings the purchase-order, receipt, and invoice totals together so you can inspect the sample records before using Select AI.

8. Establish the expected results with SQL
Run these conventional SQL checks before asking Gemini:
SELECT po_number, unreceived_invoiced_qty, unreceived_value_at_po_price
FROM invoice_reconciliation WHERE unreceived_invoiced_qty > 0;
SELECT po_number, price_variance_amount
FROM invoice_reconciliation WHERE price_variance_amount > 0;
SELECT * FROM invoices_without_po;
The fixture's expected results are:
| Check | Expected record | Expected finding |
|---|---|---|
| Invoiced quantity beyond receipts | PO-1001 | 10 units, valued at $8,000 using the PO unit price |
| Positive price variance | PO-1002 | $500 |
| Missing PO link | INV-1004 | $500 invoice line |
These are review measures with different meanings. In a larger dataset, quantity and price exceptions can overlap; do not automatically add them into a payment-hold total.
9. Create the Google OAuth credential in SQL Developer
Oracle Select AI calls Gemini from inside the database. Create a named database credential containing the Google OAuth values, then reference that credential when creating the AI profile.
- In SQL Developer, connect as SAI_DEMO using
ADBS-26ai-SAI-DEMO. - Open the ADC file from Step 4 privately on your workstation. Locate
client_id,client_secret, andrefresh_token. Copy each value without its surrounding JSON quotation marks. - Open a SQL Worksheet for SAI_DEMO and run the script below with Run Script (F5). Enter the three values when prompted.
HIDEmasks prompt entry, andSET VERIFY OFFsuppresses substitution-value echoing. - Keep the ADC file and credential-entry dialogs outside screenshots. The final verification query displays only the credential name.
For a new setup, run 09-create-google-oauth-credential.sql:
-- Run as SAI_DEMO in SQL Developer using Run Script (F5).
-- Keep the ADC file and credential-entry dialogs outside screenshots.
-- For a new setup. If the credential already exists, run only the final SELECT.
SET DEFINE ON
SET VERIFY OFF
SET ECHO OFF
ACCEPT gcp_client_id CHAR PROMPT 'Google OAuth client ID: ' HIDE
ACCEPT gcp_client_secret CHAR PROMPT 'Google OAuth client secret: ' HIDE
ACCEPT gcp_refresh_token CHAR PROMPT 'Google OAuth refresh token: ' HIDE
BEGIN
DBMS_CLOUD.CREATE_CREDENTIAL(
credential_name => 'VERTEX_OAUTH2_CRED',
params => JSON_OBJECT(
'gcp_oauth2' VALUE JSON_OBJECT(
'client_id' VALUE q'~&gcp_client_id~',
'client_secret' VALUE q'~&gcp_client_secret~',
'refresh_token' VALUE q'~&gcp_refresh_token~'
)
)
);
END;
/
UNDEFINE gcp_client_id
UNDEFINE gcp_client_secret
UNDEFINE gcp_refresh_token
SELECT credential_name
FROM user_credentials
WHERE credential_name = 'VERTEX_OAUTH2_CRED';
A successful creation reports PL/SQL procedure successfully completed. The verification query returns:
| CREDENTIAL_NAME |
|---|
| VERTEX_OAUTH2_CRED |
If VERTEX_OAUTH2_CRED already exists in your schema, run only the final verification query and reuse it for this walkthrough. The credential name is the reference used by the AI profile; it is not your database password.
This uses Oracle's documented DBMS_CLOUD.CREATE_CREDENTIAL OAuth structure. See Oracle's Google Cloud Select AI example.
10. Create the Select AI profile
Run 13-finance-profile.sql as SAI_DEMO. Enter your project ID and selected model when prompted.
-- Run as SAI_DEMO. This profile uses the existing Google OAuth credential.
SET VERIFY OFF
ACCEPT gcp_project CHAR PROMPT 'Google Cloud project ID: '
BEGIN
DBMS_CLOUD_AI.CREATE_PROFILE(
profile_name => 'GCP_GEMINI_FINANCE',
attributes => '{
"provider": "vertexai",
"credential_name": "VERTEX_OAUTH2_CRED",
"vertexai_project_id": "&gcp_project",
"region": "global",
"model": "gemini-3.5-flash-lite",
"object_list": [
{"owner":"SAI_DEMO","name":"INVOICE_RECONCILIATION"},
{"owner":"SAI_DEMO","name":"INVOICES_WITHOUT_PO"}
]
}');
END;
/
UNDEFINE gcp_project
EXEC DBMS_CLOUD_AI.SET_PROFILE('GCP_GEMINI_FINANCE');
SELECT profile_name, status FROM user_cloud_ai_profiles
WHERE profile_name = 'GCP_GEMINI_FINANCE';
The profile tells Select AI which provider, credential, project, endpoint location, model, and database views to use. Its object list provides query context; database privileges remain the access boundary. Our demonstration user owns only the sample data created for this exercise.
Set the profile again when opening a new database session:
EXEC DBMS_CLOUD_AI.SET_PROFILE('GCP_GEMINI_FINANCE');

| Setting | Purpose |
|---|---|
provider |
vertexai selects the Google Cloud model integration |
credential_name |
References the previously created Oracle credential; it contains no password or token in this script |
vertexai_project_id |
Identifies the Google Cloud project used for model requests |
region |
Selects the model endpoint location; this walkthrough uses global |
model |
Selects the Gemini model used to generate SQL |
object_list |
Identifies the two reconciliation views supplied as schema context |
CREATE_PROFILE saves the configuration. SET_PROFILE activates it for the current database session. USER_CLOUD_AI_PROFILES confirms that the profile is enabled. Set the profile again after opening a new session.
How Oracle knows which LLM to use

The AI profile is a saved configuration that tells Oracle Select AI where to send a request and how to authenticate. In this example, provider = vertexai selects the Google Cloud integration, model = gemini-3.5-flash-lite identifies the Gemini model, and region = global selects its endpoint location. The project ID identifies the Google Cloud project used for the request. VERTEX_OAUTH2_CRED references the Google OAuth credential stored in Oracle.
When the analyst asks a question, the request follows these steps:
- Our
DBMS_CLOUD_AI.GENERATEcall explicitly namesGCP_GEMINI_FINANCE, so Oracle reads that profile's settings. - Select AI prepares the provider request for the chosen action. For SQL generation, it combines the English question with metadata about the objects in
object_list, including business comments whencommentsis enabled. - Oracle uses the configured credential to authenticate and calls the Google Cloud service for the selected Gemini model.
- Gemini returns a response. For
showsql, Select AI returns generated SQL. Forrunsql, Oracle executes generated SQL using the database user's permissions. Fornarrate, query results can be sent to the model to produce the explanation.chathandles a general model conversation without querying our invoice records.
Gemini runs in Google's managed service. The invoice records and SQL calculations remain in Oracle; the information sent to the model depends on the selected action. Our NARRATE example uses fictional records and sends the query results for explanation.
The named-profile package calls used here identify their configuration explicitly on every request. SET_PROFILE also lets a session select the profile for SELECT AI statements. To use another supported provider or model, create or update the appropriate profile and supply its required authentication and endpoint settings.
See Oracle's AI profile configuration and Google authentication guide and profile attributes.
Add business context with view and column comments
Comments describe units, calculations and the meaning of finance exceptions. The profile exposes two business views, so place the relevant context on those views and their columns. Run the following as SAI_DEMO with F5, then use Ctrl+Enter on the final SELECT to display the setting in a result grid.
-- Run as SAI_DEMO in SQL Developer with F5.
COMMENT ON TABLE invoice_reconciliation IS
'Cumulative invoice and receipt totals per purchase-order line. All monetary amounts are USD before tax.';
COMMENT ON COLUMN invoice_reconciliation.unreceived_invoiced_qty IS
'Invoiced quantity exceeding received quantity. A positive value identifies an exception for finance review.';
COMMENT ON COLUMN invoice_reconciliation.unreceived_value_at_po_price IS
'Unreceived invoiced quantity valued at the purchase-order unit price in USD. A review measure, not a payment decision.';
COMMENT ON COLUMN invoice_reconciliation.price_variance_amount IS
'Invoice amount minus invoiced quantity multiplied by PO unit price. A positive value means billed price exceeds PO price.';
COMMENT ON TABLE invoices_without_po IS
'Invoice lines with no linked purchase-order line. A missing link requires investigation and does not establish a policy violation.';
BEGIN
DBMS_CLOUD_AI.SET_ATTRIBUTE(
profile_name => 'GCP_GEMINI_FINANCE',
attribute_name => 'comments',
attribute_value => 'true');
END;
/
SELECT profile_name, attribute_name,
DBMS_LOB.SUBSTR(attribute_value,100,1) AS attribute_value
FROM user_cloud_ai_profile_attributes
WHERE profile_name='GCP_GEMINI_FINANCE' AND attribute_name='comments';
The live result confirmed GCP_GEMINI_FINANCE | comments | true. With this attribute enabled, Select AI includes table and column comments in the metadata used to translate questions. Include business definitions and avoid secrets or personal data in comments because this metadata is sent to the configured AI provider.

See Oracle profile attributes for the comments setting and Oracle AI profile views for checking configured attributes.
Explain the business process with CHAT
Select AI offers different actions for different tasks. chat asks the configured model a general question without querying our invoice records. Before exploring exceptions, ask it to explain the documents involved in three-way matching. Run this script with F5 in the SAI_DEMO worksheet.
-- CHAT explains a general concept; it does not query invoice records.
-- Run as SAI_DEMO in SQL Developer with F5.
SET SERVEROUTPUT ON SIZE UNLIMITED
DECLARE
response CLOB;
BEGIN
response := DBMS_CLOUD_AI.GENERATE(
profile_name => 'GCP_GEMINI_FINANCE',
action => 'chat',
prompt => 'Explain three-way invoice matching. Give exactly three numbered lines: '
|| 'one each for purchase order, goods receipt, and supplier invoice. '
|| 'Each line must contain fewer than 90 characters. Do not query database records.'
);
DBMS_OUTPUT.PUT_LINE(response);
END;
/
The response shown below describes the purchase order as the buyer's approved document, the goods receipt as confirmation of items received, and the supplier invoice as the vendor's request for payment. These definitions provide business background; the actual invoice quantities and values come from database queries in the next steps.

The actions used in this walkthrough are:
| Action | Purpose |
|---|---|
| CHAT | Explain a general concept using the model |
| SHOWSQL | Generate SQL for review |
| RUNSQL | Generate and execute SQL against the database |
| EXPLAINSQL | Generate SQL and explain its logic; this is distinct from an optimizer execution plan |
| NARRATE | Query database records and explain the results in natural language |
See Oracle's Select AI action examples.
11. Ask the first finance question
In the SAI_DEMO worksheet, use the package interface to display the generated SQL clearly in Script Output. Run the following with F5. showsql generates SQL for review; it does not execute that SQL.
SET SERVEROUTPUT ON SIZE UNLIMITED
DECLARE
generated_sql CLOB;
BEGIN
generated_sql := DBMS_CLOUD_AI.GENERATE(
profile_name => 'GCP_GEMINI_FINANCE',
action => 'showsql',
prompt => 'For purchase order PO-1001, show the invoiced quantity, received quantity, and value of invoiced items not yet received in USD.'
);
DBMS_OUTPUT.PUT_LINE(generated_sql);
END;
/
In our live SQL Developer session, Gemini produced the following query:
SELECT
"T1"."INVOICED_QTY" AS "INVOICED_QUANTITY",
"T1"."RECEIVED_QTY" AS "RECEIVED_QUANTITY",
"T1"."UNRECEIVED_VALUE_AT_PO_PRICE" AS "UNRECEIVED_VALUE_USD"
FROM "SAI_DEMO"."INVOICE_RECONCILIATION" "T1"
WHERE "T1"."PO_NUMBER" = 'PO-1001'
The query uses the reconciliation view, selects the intended measures, and filters to the requested purchase order. Generated SQL can vary between model calls. Inspect the query, then copy the reviewed SQL into a worksheet and execute it with Ctrl+Enter. For PO-1001, the expected values are 100 invoiced units, 90 received units, and $8,000 at the purchase-order unit price. This specific-PO question continues to work after adding the synthetic records.

Execute the English question with RUNSQL
Now change the action to runsql. Select AI generates and executes SQL using the current user's database permissions. The package interface returns the result as JSON. Run the following with F5 in the SAI_DEMO worksheet.
-- RUNSQL generates and executes a query; this package call returns JSON.
-- Run as SAI_DEMO with F5.
SET SERVEROUTPUT ON SIZE UNLIMITED
DECLARE
response CLOB;
BEGIN
response := DBMS_CLOUD_AI.GENERATE(
profile_name => 'GCP_GEMINI_FINANCE',
action => 'runsql',
prompt => 'For purchase order PO-1001, show the invoiced quantity, received quantity, and value of invoiced items not yet received in USD.'
);
DBMS_OUTPUT.PUT_LINE(response);
END;
/
Our actual response was:
[
{
"INVOICED_QUANTITY": 100,
"RECEIVED_QUANTITY": 90,
"UNRECEIVED_VALUE": 8000
}
]
These values agree with the conventional SQL baseline: 100 laptops invoiced, 90 received, and ten units valued at $800 each. The JSON field names reflect the generated query and can vary between calls. RUNSQL generates a new query for its request; it does not automatically execute a previous SHOWSQL response. To execute exactly the SQL you reviewed, copy that SQL into a worksheet and run it directly.

Explain the generated SQL with EXPLAINSQL
Use explainsql to obtain SQL together with a natural-language explanation of its logic. Run this script with F5.
-- EXPLAINSQL returns SQL and an explanation, not an execution plan.
SET SERVEROUTPUT ON SIZE UNLIMITED
DECLARE
response CLOB;
BEGIN
response := DBMS_CLOUD_AI.GENERATE(
profile_name => 'GCP_GEMINI_FINANCE',
action => 'explainsql',
prompt => 'For purchase order PO-1001, show the invoiced quantity, received quantity, and value of invoiced items not yet received in USD.'
);
DBMS_OUTPUT.PUT_LINE(response);
END;
/
The response shown below explains the reconciliation object, the invoiced and received quantity columns, the USD review-value column, and the filter selecting PO-1001. This helps an analyst understand how the query relates to the question. EXPLAINSQL describes query logic; use Oracle execution-plan tools separately when investigating query performance.

Explain database results with NARRATE
Finally, use narrate to turn the query results into a business explanation. Unlike CHAT's general definitions, NARRATE uses results retrieved from our database. Query-result content can be sent to the configured model for narration; this walkthrough uses fictional records throughout. Run the following with F5.
-- NARRATE queries the database and sends results to Gemini for explanation.
-- This walkthrough uses synthetic data only.
SET SERVEROUTPUT ON SIZE UNLIMITED
DECLARE
response CLOB;
BEGIN
response := DBMS_CLOUD_AI.GENERATE(
profile_name => 'GCP_GEMINI_FINANCE',
action => 'narrate',
prompt => 'For purchase order PO-1001, explain the invoiced quantity, received quantity, '
|| 'and value of invoiced items not yet received in USD. Return three short numbered '
|| 'lines, one measure per line. Keep each line under 90 characters.'
);
DBMS_OUTPUT.PUT_LINE(response);
END;
/
The response summarizes the database results in three lines:
- Invoiced quantity: 100
- Received quantity: 90
- Value of unreceived items: $8,000 USD
These values match the conventional SQL baseline and the RUNSQL response. Finance can now see the quantity discrepancy and its review value without interpreting the JSON result. A person reviews delivery timing and payment terms before taking action.

We have now demonstrated CHAT, SHOWSQL, RUNSQL, EXPLAINSQL, and NARRATE on the same Oracle database and Google model connection.
12. Investigate other invoice exceptions
The following examples use the same finance profile. The screenshots show the explicit-profile DBMS_CLOUD_AI.GENERATE calls in SQL Developer; the equivalent SELECT AI statements are shown below. Set GCP_GEMINI_FINANCE for the current session before using them.
Find a price variance
Focus on PO-1002 so the result remains easy to compare after adding the synthetic records:
SELECT AI SHOWSQL For purchase order PO-1002, show purchase order number and price variance amount where price variance amount is positive;
SELECT AI RUNSQL For purchase order PO-1002, show purchase order number and price variance amount where price variance amount is positive;
Our RUNSQL result returned PO-1002 with a $500 price variance. Twenty monitors were invoiced at $275 each against a purchase-order price of $250: 20 × ($275 − $250) = $500.

Find an invoice without a purchase order
Ask about missing purchase-order links:
SELECT AI RUNSQL Show invoice numbers, suppliers, items and invoice amounts for invoices without a linked purchase order;
The result returned INV-1004, supplier Evergreen Office Supplies, item Consulting service, and invoice amount $500. This identifies a record for finance to investigate.

Explain unreceived invoiced quantities
Request three purchase orders to keep the explanation concise and readable:
SELECT AI NARRATE Show the first three purchase orders ordered by purchase order number with positive unreceived invoiced quantities. Explain each using unreceived quantity and value at PO price in USD. Return three short numbered lines, each under 95 characters;
The response describes PO-1001 and two generated purchase orders using their unreceived quantities and USD values at the purchase-order price.

NARRATE sends query results to the model for explanation. These examples use fictional invoice records.
13. Conclusion
We connected Oracle Autonomous Database Serverless on Google Cloud to Gemini through a Select AI profile and used everyday questions to investigate supplier invoices. The examples identified unreceived invoiced quantities, a $500 price variance, and an invoice without a linked purchase order.
CHAT explained finance concepts, SHOWSQL exposed the generated query, RUNSQL returned database results, EXPLAINSQL described the query logic, and NARRATE turned results into a readable explanation. Oracle performed the SQL calculations, while Gemini supplied the language capabilities through Google Cloud. Together, they give finance analysts a practical way to explore invoice exceptions and review the query logic behind the answers.
Additional exercise: Use synthetic data in the invoice example
The main walkthrough is complete. To try the same questions against more varied records, use this optional exercise to generate and load additional fictional procurement scenarios.
Synthetic data consists of fictional records created for testing and demonstrations. In our invoice example, it lets us explore more suppliers, purchase orders, deliveries, and invoice exceptions without using real company records.
We use Oracle's DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA with the existing GCP_GEMINI_FINANCE profile to generate 50 procurement scenarios through Gemini. Each scenario supplies an invented supplier, an item, ordered, received and invoiced quantities, and purchase-order and invoice unit prices.
First, create the SYNTHETIC_INVOICE_SEED staging table and generate ten records per call across five batches. Run the following script as SAI_DEMO in SQL Developer with F5. The prompt requests matching invoices, partial deliveries, and price differences so we can ask Select AI about several kinds of finance exception.
After generation, we will validate the rows and load them into the purchase-order, receipt, and invoice tables. The same reconciliation views and AI profile can then answer questions over the larger dataset.
-- Run as SAI_DEMO in SQL Developer with F5. Uses the existing Gemini profile.
-- New staging table keeps the original invoice fixture intact.
SET SERVEROUTPUT ON
CREATE TABLE synthetic_invoice_seed (
seed_id NUMBER(6) PRIMARY KEY,
supplier_name VARCHAR2(100) NOT NULL,
item_description VARCHAR2(100) NOT NULL,
ordered_qty NUMBER(6) NOT NULL CHECK (ordered_qty > 0),
received_qty NUMBER(6) NOT NULL CHECK (received_qty >= 0),
invoiced_qty NUMBER(6) NOT NULL CHECK (invoiced_qty > 0),
po_unit_price NUMBER(10,2) NOT NULL CHECK (po_unit_price > 0),
invoice_unit_price NUMBER(10,2) NOT NULL CHECK (invoice_unit_price > 0),
CONSTRAINT seed_received_limit CHECK (received_qty <= ordered_qty)
);
COMMENT ON TABLE synthetic_invoice_seed IS
'Fictional USD procurement scenarios for demonstration. One invoice and one PO line per seed. No real business or personal data.';
BEGIN
FOR batch_no IN 1..5 LOOP
DBMS_CLOUD_AI.GENERATE_SYNTHETIC_DATA(
profile_name => 'GCP_GEMINI_FINANCE',
object_name => 'SYNTHETIC_INVOICE_SEED',
owner_name => 'SAI_DEMO',
record_count => 10,
user_prompt => 'Create fictional enterprise purchases. Every record MUST supply all seven non-key columns: SUPPLIER_NAME, ITEM_DESCRIPTION, ORDERED_QTY, RECEIVED_QTY, INVOICED_QTY, PO_UNIT_PRICE, INVOICE_UNIT_PRICE. Never omit INVOICE_UNIT_PRICE; for matching prices set it equal to PO_UNIT_PRICE. Use positive integer ordered and invoiced quantities. Received quantity is an integer from zero to ordered quantity. Both prices are positive USD amounts with at most two decimals. Include matching invoices, partial deliveries, and price variances. Supplier names must be invented. No personal information.',
params => '{"sample_rows":0,"priority":"LOW","comments":true}'
);
DBMS_OUTPUT.PUT_LINE('Generated batch '||batch_no);
END LOOP;
END;
/
SELECT COUNT(*) AS generated_scenarios FROM synthetic_invoice_seed;
SELECT id,status,status_table FROM user_load_operations
WHERE type='SYNTHETIC_DATA' ORDER BY id DESC FETCH FIRST 3 ROWS ONLY;
Confirm that the staging count is 50 and the operation status is COMPLETED before proceeding. Review the generated values: LLM output can vary, including supplier names, prices, and exception counts. If generation reports an error, inspect its status table and current row count before retrying; a later call can append more records.

Next, validate and import those scenarios into the linked business tables. This script offsets staging identifiers by 10000, checks for invalid values and ID collisions, and inserts purchase orders, receipts, invoices, and invoice lines in one transaction. It preserves the original records and refuses to insert the same batch a second time. Zero received quantity produces no receipt row.
-- Run AFTER generation has completed and rows have been reviewed.
-- This is an explicit insert of new records, with transaction rollback on errors.
SET SERVEROUTPUT ON
-- Oracle allocates staging primary keys. Offset them for the business tables.
CREATE OR REPLACE VIEW synthetic_invoice_batch AS
SELECT seed_id+10000 AS seed_id,supplier_name,item_description,
ordered_qty,received_qty,invoiced_qty,po_unit_price,invoice_unit_price
FROM synthetic_invoice_seed;
DECLARE
invalid_rows NUMBER;
seed_rows NUMBER;
next_supplier_id NUMBER;
BEGIN
SELECT COUNT(*) INTO seed_rows FROM synthetic_invoice_batch;
IF seed_rows <> 50 THEN
RAISE_APPLICATION_ERROR(-20001, 'Expected 50 staging rows. Inspect generation status before promotion.');
END IF;
SELECT COUNT(*) INTO invalid_rows FROM synthetic_invoice_batch
WHERE seed_id < 1000 OR seed_id <> TRUNC(seed_id)
OR ordered_qty <> TRUNC(ordered_qty)
OR received_qty <> TRUNC(received_qty)
OR invoiced_qty <> TRUNC(invoiced_qty)
OR received_qty > ordered_qty OR received_qty < 0
OR ordered_qty <= 0 OR invoiced_qty <= 0
OR po_unit_price <= 0 OR invoice_unit_price <= 0;
IF invalid_rows > 0 THEN
RAISE_APPLICATION_ERROR(-20002, 'Invalid staging values. Review generated data before promotion.');
END IF;
-- Stop rather than overwriting or duplicating a previously promoted batch.
SELECT COUNT(*) INTO invalid_rows FROM synthetic_invoice_batch x
WHERE EXISTS (SELECT 1 FROM po_lines p WHERE p.po_line_id=x.seed_id)
OR EXISTS (SELECT 1 FROM invoices i WHERE i.invoice_id=x.seed_id)
OR EXISTS (SELECT 1 FROM invoice_lines l WHERE l.invoice_line_id=x.seed_id)
OR EXISTS (SELECT 1 FROM goods_receipts r WHERE r.receipt_id=x.seed_id);
IF invalid_rows > 0 THEN
RAISE_APPLICATION_ERROR(-20003, 'Generated IDs already exist. Batch was not inserted.');
END IF;
SAVEPOINT before_synthetic_batch;
BEGIN
SELECT NVL(MAX(supplier_id),0) INTO next_supplier_id FROM suppliers;
FOR x IN (SELECT DISTINCT supplier_name FROM synthetic_invoice_batch s
WHERE NOT EXISTS (SELECT 1 FROM suppliers p WHERE p.supplier_name=s.supplier_name)
ORDER BY supplier_name) LOOP
next_supplier_id := next_supplier_id + 1;
INSERT INTO suppliers VALUES (next_supplier_id, x.supplier_name);
END LOOP;
INSERT INTO po_lines (po_line_id,po_number,supplier_id,item_description,ordered_qty,po_unit_price)
SELECT x.seed_id,'PO-SYN-'||x.seed_id,s.supplier_id,x.item_description,x.ordered_qty,x.po_unit_price
FROM synthetic_invoice_batch x JOIN suppliers s ON s.supplier_name=x.supplier_name;
INSERT INTO goods_receipts (receipt_id,po_line_id,received_qty,receipt_date)
SELECT seed_id,seed_id,received_qty,DATE '2026-10-20' FROM synthetic_invoice_batch WHERE received_qty>0;
INSERT INTO invoices (invoice_id,invoice_number,supplier_id,invoice_date)
SELECT x.seed_id,'INV-SYN-'||x.seed_id,s.supplier_id,DATE '2026-10-25'
FROM synthetic_invoice_batch x JOIN suppliers s ON s.supplier_name=x.supplier_name;
INSERT INTO invoice_lines (invoice_line_id,invoice_id,po_line_id,item_description,invoiced_qty,invoice_unit_price)
SELECT seed_id,seed_id,seed_id,item_description,invoiced_qty,invoice_unit_price FROM synthetic_invoice_batch;
COMMIT;
DBMS_OUTPUT.PUT_LINE('Added 50 synthetic invoices and purchase-order lines. Original records retained.');
EXCEPTION WHEN OTHERS THEN
ROLLBACK TO before_synthetic_batch;
RAISE;
END;
END;
/
SELECT (SELECT COUNT(*) FROM suppliers) AS suppliers,
(SELECT COUNT(*) FROM po_lines) AS po_lines,
(SELECT COUNT(*) FROM goods_receipts) AS receipt_records,
(SELECT COUNT(*) FROM invoices) AS invoices,
(SELECT COUNT(*) FROM invoice_lines) AS invoice_lines
FROM dual;
SELECT po_number,supplier_name,item_description,unreceived_invoiced_qty,
unreceived_value_at_po_price,price_variance_amount
FROM invoice_reconciliation
WHERE po_line_id>=1000 ORDER BY po_line_id FETCH FIRST 10 ROWS ONLY;
The verification query below shows 50 generated scenarios, 54 total invoices, 53 purchase-order lines, 50 added invoices, and four retained original invoices.

The original baseline queries in this article apply to the original four-invoice fixture. After this extension, queries over the entire dataset include the additional scenarios. Filter reconciliation queries with po_line_id < 1000 when reproducing the original baseline amounts.
Oracle documents the generation API and operation status tables in Synthetic Data Generation.
When you have finished the walkthrough and any optional exercise, close the database connection and private tunnel. Stop the demonstration VM and database when they are no longer needed; applicable storage and other service charges can continue.
References
- Oracle Select AI profile and Google OAuth setup
- Oracle Select AI provider examples
- Oracle DBMS_CLOUD_AI package
- Google model versions and lifecycle
- Google platform overview
- Infrastructure code from Part 2
Keep your Oracle notebook growing
Get new Oracle walkthroughs in your inbox, or follow the blog in your favorite RSS reader.
Free email delivery through Blogtrottr. Enter and confirm your email on their site; unsubscribe from any email. The free service may include ads. Your email address is not collected by this blog.
Join the discussion
Ask a question, share a result, or add a useful tip.
Leave a comment
Your name and comment will be public. Keep passwords, email addresses, IP addresses, and other private details out of your comment. Cloudflare Turnstile checks submissions to help prevent spam.