Generate SQL from Natural Language Prompts Using Select AI
The Select AI feature allows Autonomous AI Database to use generative AI with Large Language Models (LLMs) to convert user's input text into Oracle SQL. Select AI processes the natural language prompt, supplements the prompt with metadata, and then generates and runs a SQL query.
About Select AI
Use natural language to interact with your database and LLMs through SQL to enhance user productivity and develop AI-based applications. Select AI simplifies and automates using generative AI, whether generating, running, and explaining SQL from a natural language prompt, using retrieval augmented generation with vector stores, generating synthetic data, or chatting with the LLM.
When you use Select AI, Autonomous AI Database manages the process of converting natural language into SQL. This means you can provide a natural language prompt instead of SQL code to interact with your data. Select AI serves as a productivity tool for SQL users and developers and enables non-expert SQL users to derive useful insights from their data, without having to understand data structures or technical languages.
Select AI also automates the retrieval augmented generation (RAG) process from generating vector embeddings to retrieving relevant content based on your prompt through semantic similarity search using your vector store. Other features include synthetic data generation, supporting chat history for conversations, and other features, all from a SQL interface.
DBMS_CLOUD_AI
package
enables
integration with a user-specified LLM for generating SQL code using natural language
prompts. For natural language to SQL generation, this package provides an augmented
prompt to the LLM containing the relevant database schema metadata. This enables
generating, running, and explaining SQL queries based on natural language
prompts.
It also facilitates retrieval augmented generation using vector stores, synthetic
data generation, and allows for chatting with the
LLM. The DBMS_CLOUD_AI package works with AI
providers listed in Select your AI Provider and LLMs.
Note:
-
You must have an account with the AI provider and provide the credentials through
DBMS_CLOUD_AIobjects that the Autonomous AI Database uses. -
You can submit prompts in multiple languages. The quality of the result depends on the abilities of the specific LLM or the embedding model (transformer) being used. Check your LLM or embedding model documentation for multi-language support.
Supported Platforms
Select AI is supported on Autonomous AI Database Serverless and Autonomous AI Database on Dedicated Exadata Infrastructure and Cloud at Customers.
- Autonomous AI Database Serverless
- Autonomous AI Database on Dedicated Exadata Infrastructure
- Autonomous AI Database on Dedicated Exadata Infrastructure Region
- Autonomous AI Database Cloud@Customer
Related Terminology
It is important to understand the various terms used with Select AI before using it.
The following are the terms related to Select AI feature:
| Term | Definition |
|---|---|
| Conversations |
Conversations in Select AI represent an interactive exchange between the user and the system, enabling users to query or interact with the database through a series of natural language prompts. Select AI incorporates session-based short-term conversations to generate context-aware responses for the current prompt based on prior interactions. Up to 10 previous prompts are incorporated into the current request with short-term conversations, creating an augmented prompt that is sent to the LLM. Select AI supports using customizable long-term conversations enabling you to use Select AI with different topics without mixing context, that can be configured through conversation APIs from the DBMS_CLOUD_AI Package. See Use and Customize Conversations for more details. |
|
Database Credential |
Database Credentials are authentication credentials used to access and interact with databases. They typically consist of a user name and a password, sometimes supplemented by additional authentication factors like security tokens. These credentials are used to establish a secure connection between an application or user and a database, ensuring that only authorized individuals or systems can access and manipulate the data stored within the database. |
|
Hallucination in LLM |
Hallucination in the context of Large Language Models refers to a phenomenon where the model generates text that is incorrect, nonsensical, or unrelated to the input prompt. Despite being a result of the model's attempt to generate coherent text, these instances can contain information that is fabricated, misleading, or purely imaginative. Hallucination can occur due to biases in training data, lack of proper context understanding, or limitations in the model's training process. |
| IAM | Oracle Cloud Infrastructure Identity and Access Management (IAM) lets you control who has access to your cloud resources. You can control what type of access a group of users have and to which specific resources. To learn more, see Overview of Identity and Access Management. |
|
Natural Language Prompts |
Natural Language Prompts are human-readable instructions or requests provided to guide generative AI models, such as Large Language Models. Instead of using specific programming languages or commands, users can interact with these models by entering prompts in a more conversational or natural language form. The models then generate output based on the provided prompt. |
|
Network Access Control List (ACL) |
A Network Access Control List is a set of rules or permissions that define what network traffic is allowed to pass through a network device, such as a router, firewall, or gateway. ACLs are used to control and filter incoming and outgoing traffic based on various criteria such as IP addresses, port numbers, and protocols. They play a crucial role in network security by enabling administrators to manage and restrict network traffic to prevent unauthorized access, potential attacks, and data breaches. |
|
Similarity Search |
Similarity search identifies and retrieves data points that closely match a given query by comparing feature vectors in a vector store. |
|
Vector Distances |
Vector distances measure the similarity or dissimilarity between feature vectors by calculating the distance between them in a multidimensional space. |
|
Vector Index |
A vector index organizes and stores feature vectors to enable efficient similarity search and retrieval of related data. |
|
Vector Store |
A vector store includes systems that store, manage, and enable semantic similarity search involving vector embeddings. This includes standalone vector databases and Oracle Database 23ai AI Vector Search. |
Select AI Use Cases
Select AI enhances data interaction and enables developers to build AI-driven applications directly from SQL, transforming natural language prompts to SQL queries and text responses, supporting chat interaction with LLMs, enhancing response accuracy with current data using RAG, and generating synthetic data.
Use cases include:
-
Generate SQL from natural language prompts
Developer productivity: Select AI significantly enhances developer productivity by providing "starter" SQL queries quickly. Developers can input natural language prompts, and Select AI generates SQL based on your database schema tables and views. This reduces the time and effort needed to write complex queries from scratch, allowing developers to focus on refining and optimizing the generated queries for their specific needs.
Natural language queries for end-users: Select AI empowers end-users to interact with your application's underlying data tables and views using natural language queries. This functionality allows users without SQL expertise to ask questions and retrieve data directly, making data access more intuitive and user-friendly relative to the capabilities of LLM being used and the quality of the schema metadata available.
Other capabilities for SQL generation: The following highlighted capabilities are also supported for natural language to SQL generation:
-
Specify schema or tables or views: Select AI enables you to specify an object list consisting of schema and optionally tables or views within that schema.
-
Automatically detect relevant table metadata: Select AI automatically detects relevant tables and send metadata only for those specific tables, relevant to the query, in Oracle Database 26ai.
- Restrict table access: Select AI enables you to restrict table access by considering only the tables listed in the AI profile attributes for SQL generation.
- Specify case sensitivity for columns: Select AI enables user to specify case sensitivity such that the LLM produces case-insensitive responses from the database and LLM.
-
-
Conversations
Enable chatbot-like features with Select AI, enabling users to have natural conversations for querying data and performing actions. These chats can keep track of context, giving follow-up answers that clarify or expand on original questions. This scenario boosts engagement and makes complicated queries easier through conversation.
-
Agentic workflows with Select AI Agent
Use Select AI Agent to coordinate agents, tools (SQL, RAG, Websearch, Notifications), and tasks for multi-step scenarios such as data retrieval, and notification. See Build Autonomous Agents with Select AI Agent to learn more.
-
Customized media generation
Select AI can be used to generate personalized media content such as emails tailored to individual customer details. For example, in your prompt you could instruct the LLM to create a friendly and upbeat email encouraging a customer to try a set of recommended products. These recommendations could be based on customer demographics or other specific information available in your database. This level of customization enhances customer engagement by delivering relevant and appealing content directly to the customer.
-
Code generation
With the Select AI
chataction, you can use Select AI to ask your specified LLM to generate code from natural language prompts. This feature supports various programming languages such as SQL, Python, R, and Java. Examples include:- Python Code: "Write the Python code to compute a confusion matrix over a DataFrame with columns ACTUAL and PREDICTED."
- SQL DDL: "Write the DDL for a SQL table with columns name, age, income, and country."
- SQL Query: "Write the SQL query that will use the Oracle Machine Learning in-database model named CHURN_DT_MODEL to predict which customers will churn and with what probability."
-
Retrieval Augmented Generation (RAG)
Use vector store content for semantic similarity search to enhance prompt accuracy and relevance in LLM responses.
-
Synthetic data generation
Generate synthetic data using LLMs that conforms to your schema for solution testing, proofs of concept, and other uses. Synthetic data can support better testing of your applications in the absence of real data, leading to overall quality of your application.
Usage Guidelines
Provides usage guidelines that ensure effective and proper usage of natural language prompts for SQL generation to ensure an enhanced user experience.
Intended Use
This feature is intended for the generation and running of SQL queries resulting from user-provided natural language prompts. It automates what a user could do manually based on their schema metadata in combination with a large language model (LLM) of their choice.
While any prompt can be provided, including those that do not relate to the
production of SQL query results, Select AI focuses on SQL query generation. Select AI
enables submitting general requests with the chat action.
Prompt Augmentation Data
The database augments the user-specified prompt with database metadata to mitigate hallucinations from the LLM. The augmented prompt is then sent to the user-specified LLM to produce the query.
The database augments the prompt with schema metadata only. This metadata may include schema definitions, table and column comments, and content available from the data dictionary and catalog. For the purposes of SQL generation, the database does not provide table or view contents (actual row or column values) when augmenting the prompt.
The narrate action, however, does provide the result of the
query, which may contain database data, to the user-specified LLM from which to generate
natural language text describing the query results.
WARNING:
Large language models (LLMs) have been trained on a broad set of text documentation and content, typically from the Internet. As a result, LLMs may have incorporated patterns from invalid or malicious content, including SQL injection. Thus, while LLMs are adept at generating useful and relevant content, they also can generate incorrect and false information including SQL queries that produce inaccurate results and/or compromise security of your data.
The queries generated on your behalf by the user-specified LLM provider will be run in your database. Your use of this feature is solely at your own risk, and, notwithstanding any other terms and conditions related to the services provided by Oracle, constitutes your acceptance of that risk and express exclusion of Oracle’s responsibility or liability for any damages resulting from that use.
Select your AI Provider and LLMs
Choose an AI provider and LLM that meets your security standards and aligns with your specific needs, like text or code generation.
Different LLMs excel at various tasks based on their training data and intended purpose. Some models are excellent for text generation but may not perform well in code generation, while others are specifically optimized for coding tasks. Choose an LLM that best suits your needs.
| AI Provider | LLMs | Embedding Model for RAG | Purpose |
|---|---|---|---|
|
OCI Generative AI |
|
|
The OCI Generative AI Chat models are supported for
all The OCI Generate text models are supported only for
To configure your profile attributes, see Profile Attributes. |
|
Azure OpenAI Service |
|
text-embedding-ada-002 |
Best suited for generating SQL from natural language
prompts, |
|
OpenAI |
|
text-embedding-ada-002 |
Best suited for generating SQL from natural language
prompts, |
|
OpenAI-Compatible |
Models from OpenAI-compatible providers such as:
|
Embedding models from OpenAI-compaitble providers. For example, see Fireworks AI embedding models. |
Supports a wide range of use cases. |
|
Cohere |
|
embed-english-v2.0 |
Best suited for |
|
|
|
text-embedding-004 (default) |
Best suited for generating SQL from natural language
prompts, |
|
Anthropic |
|
NA |
Best suited for generating SQL from natural language
prompts, |
|
Hugging Face |
|
NA |
Best suited for generating SQL from natural language
prompts, |
|
AWS |
|
Supports a wide range of use cases. |
Note:
-
Specify OpenAI-compatible provider through
provider_endpointinstead ofproviderparameter. See Profile Attributes. -
For models that accept images, use
meta.llama-3.2-90b-vision-instruct. This model is specifically trained for vision and images. While it can be used for text and SQL generation, the model is best suited for images. To learn more, see Chat in OCI Generative AI.The
meta.llama-3.2-11b-vision-instructmodel provides robust multimodal capabilities. -
Embedding models are also known as transformer models.
Configure AI Profiles Using DBMS_CLOUD_AI
Autonomous AI Database uses AI profiles to facilitate and configure access to an LLM and to setup for generating, running, and explaining SQL based on natural language prompts. It also facilitates retrieval augmented generation using embedding models and vector indexes and allows for chatting with the LLM.
AI profiles include database objects that are the target for natural language queries. Metadata used from these targets can include database table names, column names, column data types, and comments. You create and configure AI profiles using the DBMS_CLOUD_AI.CREATE_PROFILE and DBMS_CLOUD_AI.SET_PROFILE procedures.
Requirements for DBMS_CLOUD_AI
The following are required to run DBMS_CLOUD_AI:
- Access to an Oracle Cloud Infrastructure cloud account and to an Autonomous AI Database instance.
- A paid API account for a supported AI provider, one of:
-
OpenAI: To enable OpenAI to generate SQL from natural language prompts, obtain API keys from your OpenAI paid account.
You can find your secret API key in your User settings.
-
Cohere: To enable Cohere to generate SQL from natural language prompts, obtain API keys from your Cohere paid account.
Click Dashboard, and click API Keys on the left navigation. Copy the default API key or create another key. See API-Keys for more information.
-
Azure OpenAI Service: To enable Azure OpenAI Service to generate SQL from natural language prompts, configure and provide access to the AI provider.
To use Azure OpenAI Service, perform the following steps:
- Obtain your secret API keys. You can find your API keys in the Resource Management section of your Azure portal. On your Azure OpenAI Service Resource page, click Keys and Endpoint. You can copy either KEY1 or KEY2.
- Create an Azure OpenAI Service resource and deploy a model: Create and deploy an Azure OpenAI Service resource.
Tip:
- Note the resource name and deployment name as those parameters are used to provide network access permission and creating your Azure OpenAI Service profile using the
DBMS_CLOUD_AI.CREATE_PROFILEprocedure. - To know more about rate limits for token per minute on a model, see Azure OpenAI Service quotas and limits.
- Note the resource name and deployment name as those parameters are used to provide network access permission and creating your Azure OpenAI Service profile using the
- Allow access to Azure OpenAI Service:
- You can use your secret API key to allow access to Azure OpenAI Service. To know more, see the example in Examples of Using Select AI.
- OCI Generative AI: See How to Generate the API Signing Key.
- Google: To enable Google AI Studio to generate SQL and text responses to your natural language prompts, obtain API keys from your Google AI Studio paid account.
- Go to Google AI Studio.
- Click Sign In to Google AI Studio.
- Click Get API key on the prompt screen.
- Select all the applicable options on the next page.
- Click Create API key.
-
Click Create API key in new project.
The screen displays the progress and generates an API key. Copy the key and save it.
- Anthropic: To enable Anthropic Developer Console to generate SQL and text responses to your natural language prompts, obtain API keys from your Anthropic Developer Console paid account.
- Go to Anthropic Developer Console.
- Sign up for an account if you don't have one already.
- Once logged in, navigate to the API section or the dashboard.
- Look for an option to generate or view API keys.
- Click to create a new API key.
-
Copy the generated API key and save it.
The Claude API is a paid service. You'll need to add credits to your account before you can use the API key.
- Hugging Face: To enable Hugging Face as your AI provider to generate SQL and text responses to your natural language prompts, obtain API keys from your Hugging Face paid account.
- Go to Hugging Face.
- Sign up for an account if you don't have one already.
- Navigate to your account settings.
- In the navigation menu locate the Access Tokens.
- Click to create a new API key.
- Copy the generated API key and save it.
-
AWS: To enable AWS, obtain your API key and model ID.
Obtain your API key and use it to create credentials through
DBMS_CLOUD.CREATE_CREDENTIAL.Follow this process to obtain your API key and model name:
- Sign up for an AWS account if you don't have one already.
- Create your access keys and secret keys from AWS Bedrock Console.
- Copy the generated keys and save it.
- Request access to their foundation models. See Access Amazon Bedrock foundation models.
- Obtain the model ID. You require the model ID in
DBMS_CLOUD_AI.CREATE_PROFILEprocedure. Model ID depends on the resources that you use. If you use:- a base model, specify the model ID or its ARN(Amazon Resource Names). For a list of model IDs for base models, see Amazon Bedrock base model IDs
- an inference profile, specify the inference profile ID or its ARN. For a list of inference profile IDs, see Supported Regions and models for cross-region inference.
- a provisioned model, specify the ARN of the Provisioned Throughput. For more information, see Run inference using a Provisioned Throughput.
- a custom model, purchase Provisioned Throughput for it. Then, specify the ARN of the resulting provisioned model. For more information, see Use a custom model in Amazon Bedrock.
- an Amazon Bedrock Marketplace model, specify the ID or ARN of the marketplace endpoint that you created, see Amazon Bedrock Marketplace.
Note:
Imported model is not supported with Bedrock Converse API.
To use AWS as your provider, see Example: Select AI with AWS.
-
- Network ACL privileges to access your external AI provider.
Note:
Network ACL is not applicable for OCI Generative AI. - A credential that provides access to the AI provider.
DBMS_CLOUD_AI:
-
Grant the
EXECUTEprivilege on theDBMS_CLOUD_AIpackage to the user who wants to use Select AI.By default, only ADMIN user is granted the
EXECUTEprivilege. The ADMIN user can grantEXECUTEprivilege to other users.The following example grants theEXECUTEprivilege toADB_USER:grant execute on DBMS_CLOUD_AI to ADB_USER;The following example grants
ADB_USERthe privilege to use the api.openai.com endpoint.BEGIN DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE( host => 'api.openai.com', ace => xs$ace_type(privilege_list => xs$name_list('http'), principal_name => 'ADB_USER', principal_type => xs_acl.ptype_db) ); END; / -
Grant network ACL access to the user who wants to use Select AI and for the AI provider endpoint.
The ADMIN user can grant network ACL access. See APPEND_HOST_ACE Procedure in Oracle Database 19c PL/SQL Packages and Types Reference or Oracle Database 26ai PL/SQL Packages and Types Reference for more information.
- Create a credential to enable access to your AI provider.
See CREATE_CREDENTIAL Procedure for more information.
Here is an example of how to create a credential to enable access to OpenAI.
EXECDBMS_CLOUD.CREATE_CREDENTIAL('OPENAI_CRED', 'OPENAI', 'your_api_token');
APPEND_HOST_ACE Function Parameters
| Parameter | Description |
|---|---|
|
|
The host, which can be the name or the IP address of the host. You can use a wildcard to specify a domain or a IP subnet. The host or domain name is not case sensitive. For OpenAI, use api.openai.com. For Cohere, use api.cohere.ai. For Azure OpenAI Service, use <azure_resource_name>.openai.azure.com. See Profile Attributes to know more about For Google, use generativelanguage.googleapis.com. For Anthropic, use api.anthropic.com. For Hugging Face, use api-inference.huggingface.co. |
|
|
The access control entries (ACE). The |
DBMS_CLOUD.CREATE_CREDENTIAL Parameters
Create and Set an AI Profile
Describes the steps to create and enable an AI profile.
Use DBMS_CLOUD_AI.CREATE_PROFILE to create an AI profile. Next start DBMS_CLOUD_AI.SET_PROFILE to enable the AI profile so that you can use SELECT AI with a natural language prompt.
Note:
You must run DBMS_CLOUD_AI.SET_PROFILE in each new database
session (connection) before you use SELECT
AI.
The following example with the OpenAI provider creates an
AI profile called OPENAI and sets the
OPENAI profile for the current user session.
-- Create AI profile
--
SQL> BEGIN
DBMS_CLOUD_AI.create_profile(
'OPENAI',
'{"provider": "openai",
"credential_name": "OPENAI_CRED",
"object_list": [{"owner": "SH", "name": "customers"},
{"owner": "SH", "name": "sales"},
{"owner": "SH", "name": "products"},
{"owner": "SH", "name": "countries"}]
}');
END;
/
PL/SQL procedure successfully completed.
--
-- Enable AI profile in current session
--
SQL> EXEC DBMS_CLOUD_AI.set_profile('OPENAI');
PL/SQL procedure successfully completed.
Use AI Keyword to Enter Prompts
Use AI as the keyword in a SELECT
statement for interacting with the database using natural language prompts.
The AI keyword in a SELECT statement
instructs the SQL execution engine to use the LLM identified in the active AI profile to
process natural language and to generate SQL.
You can use the AI keyword in a query with Oracle clients
such as SQL Developer, OML Notebooks, and third-party tools, to interact with database
in natural language.
Note:
You cannot run PL/SQL statements, DDL statements, or DML statements using theAI keyword.
Syntax
SELECT AI action natural_language_promptParameters
| Parameter | Description |
|---|---|
|
|
Run the provided SQL command using a natural language prompt. This is the default action and it is optional to specify this parameter. |
|
|
Displays the SQL statement for a natural language prompt. |
|
|
The output of the prompt is explained in natural language. This option sends the SQL result to the AI provider to produce a natural language summary. |
|
|
Generates
a response directly from the LLM based on the prompt. If
|
|
|
The SQL generated from the prompt is explained in natural language. This option sends the generated SQL to the AI provider to produce a natural language explanation. |
Usage Notes
-
Select
AIis not supported in Database Actions or APEX Service. You can use onlyDBMS_CLOUD_AI.GENERATEfunction. -
The
AIkeyword is supported only in aSELECTstatement. -
You cannot run PL/SQL statements, DDL statements, or DML statements using the
AIkeyword. -
The sequence is
SELECTfollowed byAI. These keywords are not case-sensitive. After aDBMS_CLOUD_AI.SET_PROFILEis configured, the text afterSELECT AIis a natural language prompt. If an AI profile is not set,SELECTAIreports the following error:ORA-00923: FROM keyword not found where expected 00923. 00000 - "FROM keyword not found where expected" -
Special character usage rules apply according to Oracle guidelines. For example, use single quotes twice if you are using an apostrophe in a sentence.
select ai how many customers in SF don''t own their own home -
LLMs are subject to hallucinations and results are not always correct:
-
It is possible that
SELECT AImay not be able to run the generated SQL for a specific natural language prompt. -
It is possible that
SELECT AImay not be able to generate SQL for a specific natural language prompt.
In such a scenario,
SELECT AIresponds with information to assist you in generating valid SQL. -
-
Use the
chataction, withSELECT AI chat, to learn more about SQL constructs. For better results with thechataction, use database views or tables with contextual column names or consider adding column comments explaining values stored in the columns. -
To access DBA or USER views, see DBMS_CLOUD_AI Views.
Use and Customize Conversations
Select AI supports short-term, session-based conversations, which are enabled in the AI profile, as well as long-term, named conversations, which are enabled using specific procedures or functions and conversation IDs.
Note:
Support for Select AI Conversations is available in Oracle Database 19c starting with version 19.30, and in Oracle Database 26ai starting with version 23.26.1.Types of Conversations
Select AI supports session-based short-term conversations and customizable conversations.
Session-based Short-Term Conversations: Select AI includes session-based short-term conversations to generate context-aware responses for the current prompt based on prior interactions.
You can enable it by setting the conversation attribute
to true|false in your AI profile. Unlike the multiple conversation
feature, session-based conversations store prompts only for the duration of the
session. Prompts are stored in a temporary table, automatically dropped when the
session ends, and cannot be reused and switched among conversations.
Customizable Long-Term Conversations:
Select AI supports creating and using customizable conversations enabling you to use
Select AI with different topics without mixing context, improving both flexibility
and efficiency. You can create, set, delete, and update conversations through the
DBMS_CLOUD_AI conversation procedures and functions. When you
enable conversations, Select AI retrieves prompt history and sends them to the LLM
to generate a response for the current prompt. These responses are stored in a
persistent table for future use.
Note:
Select AI Conversations support the following actions:runsql, showsql,
explainsql, narrate, and
chat.
How to Use Customizable Conversations
You can use Select AI for customizable conversations in the following ways:
-
Set the conversation ID in the session using the
DBMS_CLOUD_AI.SET_CONVERSATION_IDprocedure, and runSELECT AI <ACTION> <PROMPT>. -
Pass the
conversation_idin theparamsargument of theDBMS_CLOUD_AI.GENERATEfunction.
Note:
If you use both multiple conversations and theconversation: [true|false] setting, the
system ignores the conversation setting.
In the context of SQL query generation (NL2SQL), conversations enable a more intuitive and accessible way to work with your data, making it easier for users to extract insights and perform tasks without needing deep technical knowledge of SQL. Conversations can also be used with chat and RAG capabilities of Select AI.
- Ask a question such as "What are the total number of customers"
- Follow up with context aware questions like:
- "break out count of customers by country"
- "What age group is most common"
- "keep the top 5 customers and their country by their purchases and include a rank in the result"
To enable conversations, see Example: Enable Conversations in Select AI for a complete example.
Session-Based Conversations vs Customizable Conversations
The following table compares the session-based conversation and the customizable conversations in Select AI:
| Questions | Session-Based Short-Term Conversations | Customizable Long-Term Conversations |
|---|---|---|
|
When do I use? |
Best for quick, temporary chats where you want the model to remember recent questions and answers during a single session. It’s useful when you don’t need to save or reuse the conversation later. |
Designed for longer or ongoing conversations that may span multiple sessions. It’s useful when you want to track, review, or manage the conversation history, or when different parts of an application need to access the same conversation context over time. |
|
How do I enable? |
Set |
Use the |
|
How many conversations are permitted? |
One. |
You can create multiple conversations. If you explicitly specify conversation IDs, you can alternate between them to associate prompts with the appropriate conversations as needed. |
|
Where are prompts stored and for how long? |
Prompts are stored in a temporary table and dropped when the session ends. |
Prompts are stored in a permanent table. Prompts are retained in the database for the number of days specified by the |
|
How many prompts are stored and how many prompts are sent to the LLM? |
A maximum of 10 prompts are stored and sent to the LLM. You cannot customize this limit. |
All prompts are stored. By default, the system sends the 10 most recent prompts to the LLM. You can customize this using the |
|
Can I delete individual prompts? |
No, you cannot delete individual prompt manually. |
You can delete specific individual prompts by using the prompt id as specified in the USER_CLOUD_AI_CONVERSATION_PROMPTS View and using the |
|
Are AI profiles used for retrieval of conversations? |
Yes, Select AI retrieves prompts and responses previously generated using the same AI profile. |
No, Select AI tracks the AI profile used when storing prompts and responses but does not restrict their retrieval based on that profile. It sends all conversation histories to the LLM to guide response generation, regardless of the profile used to generate them. |
|
Where can I check history of prompts? |
Prompts are saved in a temporary table under CLOUD USER but are not accessible for querying. |
You can query and review conversations and prompts through the |
Provide Feedback to Improve LLMs
Select AI enables you to provide feedback to help improve your selected LLM's ability to generate more accurate SQL queries.
Note:
This feature is available only on Oracle Database 23ai. You can use it alongside the existing Select AI actions: runsql, showsql, and explainsql. Ensure that your AI profile is configured for NL2SQL generation and not RAG.
You can provide feedback to improve the accuracy of the generated SQL through the feedback action or the DBMS_CLOUD_AI.FEEDBACK procedure. Select AI creates a default vector index named <profile_name>_FEEDBACK_VECINDEX with default attributes when you use the feedback feature for the first time. This index helps refine future generated SQL based on the feedback provided. See Vector Index for FEEDBACK for more information.
Tip:
Use the DBMS_CLOUD_AI.FEEDBACK procedure when your specified LLM fails to generate the correct SQL query or does not return the expected result from one of the NL2SQL SELECT AI actions. You can also use the DBMS_CLOUD_AI.FEEDBACK procedure to add the correct SQL directly to the vector table. This helps guide future SQL generation by serving as a reference for similar prompts.
-
Positive feedback: You approve and confirm the accuracy of the generated SQL. The system stores the confirmed query for future reference.
-
Negative feedback: If the results from your NL2SQL
SELECT AIaction fails to generate the correct SQL, you can provide the necessary SQL query improvements usingSELECT AI feedback <feedback>or using theDBMS_CLOUD_AI.FEEDBACKprocedure by identifying errors in the query or providing guidance as to what was expected in prose. The system refines the query using an LLM and stores the refined version for future Select AI query generation. The stored refined queries are then used as hints and sent to the LLM as part of the augmented prompt.
Benefits of Using Feedback
The feedback action and procedure in Select AI introduces a prompt tuning mechanism that enhances the accuracy of SQL query generation.
- Can improve accuracy of SQL queries.
- Enables the owner of AI profile to provide feedback by confirming the correct queries or suggesting corrections by providing the semantic intention or business definitions to produce a correct query.
- Uses historical feedback as hints for future query generation thereby adapting to your needs.
How to Provide Feedback
Select AI enables you to provide feedback either by using the feedback action or by calling the DBMS_CLOUD_AI.FEEDBACK procedure.
Caution:
Do not use the feedback action in applications where multiple users share database sessions under a single database user that owns the AI profile. The AI profile owner should provide feedback only after confirming that the corrected query is appropriate for all users of that profile.
-
SQL_TEXT: Include the feedback in quotes for your current SQL query or you can get theSQL_TEXTfor a particular query by querying theV$MAPPED_SQLview. -
SQL_ID: You can get theSQL_IDby querying theV$MAPPED_SQLview. -
Use the last generated SQL: Provide your feedback in natural language.
Note:
To use last sql, be sure to set server output off in Oracle SQL*Plus or Oracle SQLcl. You must haveREADprivilege onsys.v_$sessionandv_$mapped_sqltables.GRANT READ ON SYS.V_$MAPPED_SQL TO ADB_USER; GRANT READ ON SYS.V_$SESSION TO ADB_USER;
See FEEDBACK Procedure and Example: Select AI Feedback to learn more.
Query Graph Data with Property Graphs
Select AI generates Property Graph Query (PGQ) on Oracle Property Graphs using natural language. It enables users to query graph data through the GRAPH_TABLE operator with minimal SQL knowledge.
Select AI extends its natural language to SQL (NL2SQL) capability to graph structures enabling you to query SQL Property Graphs using natural language. Select AI applies the GRAPH_TABLE operator to interpret relationships and attributes in graph-structured data. It generates SQL or PGQ graph queries based on the data objects defined in the AI profile. When a property graph is included in the AI profile, Select AI uses generative AI to build a PGQ query that references the graph through the GRAPH_TABLE operator. The LLM automatically receives the graph object's metadata such as CREATE PROPERTY GRAPH statements to generate accurate queries. When a table, view, or relational object is specified, Select AI generates a SQL query. This capability simplifies pattern-matching queries on graph data stored in Oracle AI Database and reduces dependency on manually constructing SQL queries.
object_list attribute, the LLM defined in AI profile interprets prompts by using the context of the specified property graphs. Select AI builds an augmented prompt that includes:
-
Instructions to construct PGQ queries.
-
Metadata describing the provided property graphs (from their
CREATE PROPERTY GRAPHstatements).
This augmented prompt is sent to the LLM. Select AI runs the query and returns results. If a property graph is specified along with other object types such as tables, schema, or views in the AI profile, Select AI raises an error.
SQL vs PGQ
object_list attribute of your AI profile.
-
SQL Query: uses relational data such as schema, tables, or views.
-
PGQ Query: uses property graphs and applies the
GRAPH_TABLEoperator for pattern matching.
See SQL Property Graph and SQL GRAPH Queries for more details.
Benefits of Using Select AI on Property Graphs
Database users can query property graphs using Select AI to generate graph queries from natural language, reducing manual work and improving understanding of graph relationships.
-
NL2SQL: Select AI’s NL2SQL capability now extends to graph queries enabling users to write natural language prompts such as “Find customers who bought a dress”.
-
SQL or PGQ: Depending on the data object, Select AI automatically generates SQL or PGQ query.
-
Productivity: Reduces time and effort in building graph queries using the
GRAPH_TABLEoperator. -
Conversations: Retains conversation context and queries a property graph.
Limitations
Select AI for Property Graphs does not support the following capabilities:
-
Synthetic data generation
-
Mixing of property graphs with other object types in the AI profile
-
Unsupported and intermittent queries. See Example: Sample Prompts for Property Graphs for more details.
How to Use Select AI on Property Graphs
Select AI enables you to explore graph data by using the DBMS_CLOUD_AI.GENERATE function or by using Select AI <action> <prompt>.
object_list attribute of your AI profile, you can use:
-
SELECT AI <ACTION> <PROMPT>in the SQL command line to generate an output. -
DBMS_CLOUD_AI.GENERATEfunction and supply your prompt within the function.
The following are the supported actions: runsql, showsql, explainsql, narrate, and showpropmt. Select AI for Property Graph also supports session-based short-term and customizable long-term conversations.
See Example: Select AI for Property Graphs and Example: Sample Prompts for Property Graphs to learn more.
Examples of Using Select AI
Explore integrating Oracle's Select AI with various supported AI providers to generate, run, and explain SQL from natural language prompts or chat with the LLM.
Example: Select AI Actions
The following example illustrates actions such as runsql (the default), showsql, narrate, chat, explainsql, feedback, and summarize that you can perform with SELECT AI. These examples use the sh schema with AI provider and profile attributes specified in the DBMS_CLOUD_AI.CREATE_PROFILE function. Use Select AI actions after setting your AI profile by using the DBMS_CLOUD_AI.SET_PROFILE procedure in the current session.
To generate a summary of your text, use SELECT AI SUMMARIZE <TEXT>.
SQL> select ai how many customers exist;
CUSTOMER_COUNT
--------------
55500
SQL> select ai showsql how many customers exist;
RESPONSE
----------------------------------------------------
SELECT COUNT(*) AS total_customers
FROM SH.CUSTOMERS
SQL> select ai narrate how many customers exist;
RESPONSE
------------------------------------------------------
There are a total of 55,500 customers in the database.
SQL> select ai chat how many customers exist;
RESPONSE
--------------------------------------------------------------------------------
It is impossible to determine the exact number of customers that exist as it con
stantly changes due to various factors such as population growth, new businesses
, and customer turnover. Additionally, the term "customer" can refer to individu
als, businesses, or organizations, making it difficult to provide a specific num
ber.
SQL> select ai explainsql how many customers in San Francisco are married;
RESPONSE
--------------------------------------------------------------------------------
SELECT COUNT(*) AS customer_count
FROM SH.CUSTOMERS AS c
WHERE c.CUST_STATE_PROVINCE = 'San Francisco' AND c.CUST_MARITAL_STATUS = 'Married';
Explanation:
- We use the 'SH' table alias for the 'CUSTOMERS' table for better readability.
- The query uses the 'COUNT(*)' function to count the number of rows that match the given conditions.
- The 'WHERE' clause is used to filter the results:
- 'c.CUST_STATE_PROVINCE = 'San Francisco'' filters customers who have 'San Francisco' as their state or province.
- 'c.CUST_MARITAL_STATUS = 'Married'' filters customers who have 'Married' as their marital status.
The result of this query will give you the count of customers in San Francisco who are married, using the column alias 'customer_count' for the result.
Remember to adjust the table and column names based on your actual schema if they differ from the example.
Feel free to ask if you have more questions related to SQL or database in general.
-- Feedback on SQL Text
-- Negative feedback example:
SQL > select ai feedback for query "select ai showsql how many watch histories in total", please use sum instead of count;
-- Positive feedback example:
SQL > select ai feedback for query "select ai showsql how many watch histories in total", the sql query generated is correct;
-- Feedback on SQL ID
-- Negative feedback example:
SQL > select ai feedback please use sum instead of count for sql_id 1v1z68ra6r9zf;
-- Positive feedback example:
SQL > select ai feedback sql query result is correct for sql_id 1v1z68ra6r9zf;
-- If not specified, use default LASTAI SQL
-- To use default LASTAI sql, make sure that set server output off;
-- Negative feedback example:
SQL > select ai feedback please use ascending sorting for ranking;
-- Positive feedback example:
SQL > select ai feedback the result is correct;
SQL> SELECT AI SUMMARIZE
Like countless other people around the globe, I stream music, and like more
than six hundred million of them I mainly use Spotify. Streaming currently
accounts for about eighty per cent of the American recording industry’s
revenue, and in recent years Spotify’s health is often consulted as a measure
for the health of the music business over all. Last spring, the International
Federation of the Phonographic Industry reported global revenues of $28.6
billion, making for the ninth straight year of growth. All of this was
unimaginable in the two-thousands, when the major record labels appeared
poorly equipped to deal with piracy and the so-called death of physical media.
On the consumer side, the story looks even rosier. Adjusted for inflation, a
... (skipped 1000 rows in the middle)
Pelly writes of some artists, in search of viral fame, who surreptitiously use
social media to effectively beta test melodies and motifs, basically putting
together songs via crowdsourcing. Artists have always fretted about the
pressure to conform, but the data-driven, music-as-content era feels
different. “You are a Spotify employee at that point,” Daniel Lopatin, who
makes abstract electronic music as Oneohtrix Point Never, told Pelly. “If your
art practice is so ingrained in the brutal reality that Spotify has outlined
for all of us, then what is the music that you’re not making? What does the
music you’re not making sound like?” Listeners might wonder something similar.
What does the music we’re not hearing sound like?;
RESPONSE
------------------------------------------------------------------------------
The music streaming industry, led by Spotify, has revolutionized the way
people consume music, with streaming accounting for 80% of the American
recording industry's revenue. However, this shift has also complicated the
lives of artists, who struggle to survive in a hyper-abundant present where
music is often valued for its convenience rather than its artistic merit.
Spotify's algorithms prioritize popularity and profitability over artistic
diversity, leading to a homogenization of music and a devaluation of the
labor that goes into creating it. Meanwhile, the company's executives reap
enormous profits, with CEO Daniel Ek's net worth rivaling that of the
wealthiest musicians. As music critic Liz Pelly argues, the streaming economy
raises important questions about autonomy, creativity, and the value of art
in a world where everything is readily available and easily accessible.Example: Select AI with AWS
This example shows how you can use AWS to generate, run, and explain SQL from natural language prompts or chat using the models available with AWS.
The following example shows how to use AWS as the AI provider with Amazon Bedrock and its foundation models. The example shows creating AWS credentials, provide network access, creating an AI profile, and using Select AI actions to generate SQL queries from natural language prompts and chat using the AWS foundation models.
To use AWS, obtain access key, secret keys, and model ID. See . Use the model ID as the model attribute in the DBMS_CLOUD_AI.CREATE_PROFILE procedure. You must specify the model attribute explicitly, as no default model is provided.
--Grant EXECUTE privilege to ADB_USER
GRANT EXECUTE on DBMS_CLOUD_AI to ADB_USER;
--
-- Create Credential for AI provider
--
BEGIN
DBMS_CLOUD.CREATE_CREDENTIAL(
credential_name => 'AWS_CRED',
username => '<your_AWS_access_key>',
password => '<your_AWS_secret_key>'
);
END;
/
PL/SQL procedure successfully completed.
--
-- Grant Network ACL for AWS
--
BEGIN
DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(
host => 'bedrock-runtime.us-east-1.amazonaws.com',
ace => xs$ace_type(privilege_list => xs$name_list('http'),
principal_name => 'ADB_USER',
principal_type => xs_acl.ptype_db)
);
END;
/
PL/SQL procedure successfully completed.
--
-- Create AI profile
--
BEGIN
DBMS_CLOUD_AI.CREATE_PROFILE(
profile_name =>'AWS',
attributes =>'{"provider": "aws",
"credential_name": "AWS_CRED",
"object_list": [{"owner": "SH", "name": "customers"},
{"owner": "SH", "name": "countries"},
{"owner": "SH", "name": "supplementary_demographics"},
{"owner": "SH", "name": "profits"},
{"owner": "SH", "name": "promotions"},
{"owner": "SH", "name": "products"}],
"model" : "anthropic.claude-v2",
"conversation" : "true"
}');
END;
/
PL/SQL procedure successfully completed.
--
-- Enable AI profile in current session
--
EXEC DBMS_CLOUD_AI.SET_PROFILE('AWS');
PL/SQL procedure successfully completed.
--
-- Use AI
--
SELECT AI how many customers exist;
"RESPONSE"
"COUNT(*)"
55500
SELECT AI how many customers in San Francisco are married;
"RESPONSE"
"COUNT(*)"
46
SELECT AI showsql how many customers in San Francisco are married;
"RESPONSE"
"SELECT COUNT(*) AS "Number of Married Customers in San Francisco"
FROM "SH"."CUSTOMERS" C
WHERE UPPER(C."CUST_CITY") = UPPER('San Francisco')
AND UPPER(C."CUST_MARITAL_STATUS") = UPPER('Married')"
SELECT AI explainsql how many customers in San Francisco are married;
"RESPONSE""SELECT
COUNT(*) AS "Number of Married Customers in San Francisco"
FROM "SH"."CUSTOMERS" C
WHERE C."CUST_CITY" = 'San Francisco'
AND C."CUST_MARITAL_STATUS" = 'Married'
Explanation:
- Used table alias C for CUSTOMERS table
- Used easy to read column names like CUST_CITY, CUST_MARITAL_STATUS
- Enclosed table name, schema name and column names in double quotes
- Compared string values in WHERE clause without UPPER() since the values are not in double quotes
- Counted number of rows satisfying the condition and aliased the count as "Number of Married Customers in San Francisco""
SELECT AI narrate what are the top 3 customers in San Francisco;
"RESPONSE"
The top 3 customers in San Francisco ordered by credit limit in descending order are:
1. Bert Katz
2. Madallyn Ladd
3. Henrietta Snodgrass
SELECT AI chat what is Autonomous AI Database;
"RESPONSE"
"An Autonomous AI Database is a cloud database service provided by Oracle Corporation. Some key features of Oracle Autonomous AI Database include:
- Fully automated and self-driving - The database automatically upgrades, patches, tunes, and backs itself up without any human intervention required.
- Self-securing - The database uses machine learning to detect threats and automatically apply security updates.
- Self-repairing - The database monitors itself and automatically recovers from failures and errors without downtime.
- Self-scaling - The database automatically scales compute and storage resources up and down as needed to meet workload demands.
- Serverless - The database is accessed as a cloud service without having to manually provision any servers or infrastructure.
- High performance - The database uses Oracle's advanced automation and machine learning to continuously tune itself for high performance.
- Multiple workload support - Supports transaction processing, analytics, graph processing, etc in a single converged database.
- Fully managed - Oracle handles all the management and administration of the database. Users just load and access their data.
- Compatible - Supports common SQL and Oracle PL/SQL for easy migration from on-prem Oracle databases.
So in summary, an Oracle Autonomous AI Database is a fully automated, self-driving, self-securing, and self-repairing database provided as a simple cloud service. The automation provides high performance, elasticity, and availability with minimal human labor required."
--
--Clear the profile
--
BEGIN
DBMS_CLOUD_AI.CLEAR_PROFILE;
END;
/
PL/SQL procedure successfully completed.
--
--Drop the profile
--
EXEC DBMS_CLOUD_AI.DROP_PROFILE('AWS');
PL/SQL procedure successfully completed.Example: Enable Conversations in Select AI
These examples illustrates enabling conversations in Select AI.
Note:
A user with administrator privileges (ADMIN) must grant EXECUTE and enable network access control list (ACL).
Session-Based Conversations
Create your AI profile. Set the conversation attribute to true in the profile, this action includes content from prior interactions or prompts, potentially including schema metadata, and set your profile. Once the profile is enabled, you can begin having conversations with your data. Use natural language to ask questions and follow up as needed.
--Grants EXECUTE privilege to ADB_USER
--
SQL> grant execute on DBMS_CLOUD_AI to ADB_USER;
-- Grant Network ACL for OpenAI endpoint
--
SQL> BEGIN
DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(
host => 'api.openai.com',
ace => xs$ace_type(privilege_list => xs$name_list('http'),
principal_name => 'ADB_USER',
principal_type => xs_acl.ptype_db)
);
END;
/
PL/SQL procedure successfully completed.
--
-- Create Credential for AI provider
--
EXEC
DBMS_CLOUD.CREATE_CREDENTIAL(
CREDENTIAL_NAME => 'OPENAI_CRED',
username => 'OPENAI',
password => '<your_api_token>');
PL/SQL procedure successfully completed.
--
-- Create AI profile
--
BEGIN
DBMS_CLOUD_AI.CREATE_PROFILE(
profile_name => 'OPENAI',
attributes =>'{"provider": "openai",
"credential_name": "OPENAI_CRED",
"object_list": [{"owner": "SH", "name": "customers"},
{"owner": "SH", "name": "countries"},
{"owner": "SH", "name": "supplementary_demographics"},
{"owner": "SH", "name": "profits"},
{"owner": "SH", "name": "promotions"},
{"owner": "SH", "name": "products"}],
"conversation": "true"
}');
END;
/
PL/SQL procedure successfully completed.
--
-- Enable AI profile in current session
--
SQL> EXEC DBMS_CLOUD_AI.SET_PROFILE('OPENAI');
PL/SQL procedure successfully completed.
--
-- Get Profile in current session
--
SQL> SELECT DBMS_CLOUD_AI.get_profile() from dual;
DBMS_CLOUD_AI.GET_PROFILE()
--------------------------------------------------------------------------------
"OPENAI"
--
-- Use AI
--
what are the total number of customers;
CUSTOMER_COUNT
--------------
55500
break out count of customers by country;
RESPONSE
-----------------
COUNTRY_NAME CUSTOMER_COUNT
Italy 7780
Brazil 832
Japan 624
United Kingdom 7557
Germany 8173
United States of America 18520
France 3833
Canada 2010
Spain 2039
China 712
Singapore 597
New Zealand 244
Poland 708
Australia 831
Argentina 403
Denmark 383
South Africa 88
Saudi Arabia 75
Turkey 91
what age group is most common;
RESPONSE
--------------------------------------------------------------------------------
AGE_GROUP CUSTOMER_COUNT
65+ 28226
select ai keep the top 5 customers and their country by their purchases and include a rank in the result;
RESPONSE
--------------------------------------------------------------------------------
RANK CUSTOMER_NAME COUNTRY PURCHASES
1 Abigail Ruddy Japan 276
2 Abigail Ruddy Italy 168
3 Abigail Ruddy Japan 74
3 Abner Robbinette Germany 74
5 Abner Everett France 68
SQL> EXEC DBMS_CLOUD_AI.DROP_PROFILE('OPENAI');
PL/SQL procedure successfully completed.Customizable Conversations
- Create a conversation
- Set the conversation in the current user session
- Use
Select AI <action> <prompt>
- Use
DBMS_CLOUD_AI.CREATE_CONVERSATIONfunction and then set the conversation usingDBMS_CLOUD_AI.SET_CONVERSATION_ID. - Call the
DBMS_CLOUD_AI.CREATE_CONVERSATIONprocedure directly to create and set the conversation in one step.
The following example demonstrates how to create a conversation using DBMS_CLOUD_AI.CREATE_CONVERSATION function and set it using the DBMS_CLOUD_AI.SET_CONVERSATION_ID procedure.
SELECT DBMS_CLOUD_AI.CREATE_CONVERSATION; -- in 19c, run SELECT DBMS_CLOUD_AI.create_conversation FROM dual;
CREATE_CONVERSATION
------------------------------------
30C9DB6E-EA4D-AFBA-E063-9C6D46644B92
EXEC DBMS_CLOUD_AI.SET_CONVERSATION_ID('30C9DB6E-EA4D-AFBA-E063-9C6D46644B92');
PL/SQL procedure successfully completedThe following example demonstrates running the DBMS_CLOUD_AI.CREATE_CONVERSATION procedure to create and set the conversation_id directly.
EXEC DBMS_CLOUD_AI.create_conversation;
PL/SQL procedure successfully completed.You can also customize the conversation attributes such as title, description, retention_days, and conversation_length attributes.
SELECT DBMS_CLOUD_AI.CREATE_CONVERSATION(
attributes => '{"title":"My first conversation",
"description":"this is my first conversation",
"retention_days":5,
"conversation_length":5}');
CREATE_CONVERSATION
------------------------------------
38F8B874-7687-2A3F-E063-9C6D4664EC3AYou can view if a certain conversation exists by querying DBA/USER_CLOUD_AI_CONVERSATIONS view.
-- Verify the setup
SELECT conversation_id, conversation_title, description, retention_days,
conversation_length FROM DBA_CLOUD_AI_CONVERSATIONS WHERE
conversation_id = '38F8B874-7687-2A3F-E063-9C6D4664EC3A';
CONVERSATION_ID CONVERSATION_TITLE DESCRIPTION RETENTION_DAYS CONVERSATION_LENGTH
------------------------------------ ----------------------------------------------- ---------------------------------- ------------------------------ -------------------
38F8B874-7687-2A3F-E063-9C6D4664EC3A My first conversation this is my first conversation +00005 00:00:00.000000 5
You can also verify if a conversation is set by calling the DBMS_CLOUD_AI.GET_CONVERSATION_ID function.
SELECT DBMS_CLOUD_AI.GET_CONVERSATION_ID;
--------------------------------------------------------------------------------
30C9DB6E-EA4F-AFBA-E063-9C6D46644B92After you create and set the conversation and enable your AI profile, you can start interacting with your data. Use natural language to ask questions and follow up as needed.
Use SELECT AI <ACTION> <PROMPT>.
SELECT AI CHAT What is the difference in weather between Seattle and San Francisco?;
RESPONSE
--------------------------------------------------------------------------------
Seattle and San Francisco are both located on the West Coast of the United State
s, but they have distinct weather patterns due to their unique geography and cli
mate conditions. Here are the main differences:
1. **Rainfall**: Seattle is known for its rainy reputation, with an average annu
al rainfall of around 37 inches (94 cm). San Francisco, on the other hand, recei
ves significantly less rainfall, with an average of around 20 inches (51 cm) per
year.
2. **Cloud Cover**: Seattle is often cloudy, with an average of 226 cloudy days
per year. San Francisco is also cloudy, but to a lesser extent, with an average
of 165 cloudy days per year.
......
SELECT AI CHAT Explain the difference again in one paragraph only.;
RESPONSE
--------------------------------------------------------------------------------
Seattle and San Francisco have different weather patterns despite both experienc
ing a mild oceanic climate. San Francisco tends to be slightly warmer, with aver
age temperatures ranging from 45?F to 67?F, and receives less rainfall, around 2
0 inches per year, mostly during winter. In contrast, Seattle is cooler, with te
mperatures ranging from 38?F to 64?F, and rainier, with around 37 inches of rain
fall per year, distributed throughout the year. San Francisco is also known for
its fog, particularly during summer, and receives more sunshine, around 160 sunn
y days per year, although it's often filtered through the fog. Overall, San Fran
cisco's weather is warmer and sunnier, with more pronounced seasonal variations,
while Seattle's is cooler and rainier, with more consistent temperatures throug
hout the year.The following example show how two conversations are used interchangeably to ask questions and verify accurate responses. Each conversation begins with a different question focused on comparison. Later, when you ask the same follow-up question in both conversations, each returns a different answer based on its prior context.
-- First conversation
SELECT DBMS_CLOUD_AI.CREATE_CONVERSATION;
CREATE_CONVERSATION
------------------------------------
30C9DB6E-EA4D-AFBA-E063-9C6D46644B92
-- Second conversation
SELECT DBMS_CLOUD_AI.CREATE_CONVERSATION;
CREATE_CONVERSATION
------------------------------------
30C9DB6E-EA4E-AFBA-E063-9C6D46644B92
-- Call generate using the first conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
prompt => 'What is the difference in weather between Seattle and San Francisco?',
profile_name => 'GENAI',
action => 'CHAT',
params => '{"conversation_id":"30C9DB6E-EA4D-AFBA-E063-9C6D46644B92"}') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
Seattle and San Francisco, both located in the Pacific Northwest and Northern Ca
lifornia respectively, experience a mild oceanic climate. However, there are som
e notable differences in their weather patterns:
1. **Temperature**: San Francisco tends to be slightly warmer than Seattle, espe
cially during the summer months. San Francisco's average temperature ranges from
45?F (7?C) in winter to 67?F (19?C) in summer, while Seattle's average temperat
ure ranges from 38?F (3?C) in winter to 64?F (18?C) in summer.
2. **Rainfall**: Seattle is known for its rainy reputation, with an average annu
al rainfall of around 37 inches (94 cm). San Francisco receives less rainfall, w
ith an average of around 20 inches (51 cm) per year. However, San Francisco's ra
infall is more concentrated during the winter months, while Seattle's rainfall i
s more evenly distributed throughout the year.
......
-- Call generate using the second conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
prompt => 'How does the cost of living compare between New York and Los Angeles?',
profile_name => 'GENAI',
action => 'CHAT',
params => '{"conversation_id":"30C9DB6E-EA4E-AFBA-E063-9C6D46644B92"}') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
The cost of living in New York and Los Angeles is relatively high compared to ot
her cities in the United States. However, there are some differences in the cost
of living between the two cities. Here's a comparison of the cost of living in
New York and Los Angeles:
1. Housing: The cost of housing is significantly higher in New York than in Los
Angeles. The median home price in New York is around $999,000, while in Los Ange
les it's around $849,000. Rent is also higher in New York, with the average rent
for a one-bedroom apartment being around $3,000 per month, compared to around $
2,400 per month in Los Angeles.
2. Food: The cost of food is relatively similar in both cities, with some variat
ion in the cost of certain types of cuisine. However, eating out in New York can
be more expensive, with the average cost of a meal at a mid-range restaurant be
ing around $15-20 per person, compared to around $12-18 per person in Los Angele
s.
......
-- Call generate using the first conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
prompt => 'Explain the difference again in one paragraph only.',
profile_name => 'GENAI',
action => 'CHAT',
params => '{"conversation_id":"30C9DB6E-EA4D-AFBA-E063-9C6D46644B92"}') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
Seattle and San Francisco have different weather patterns despite both experienc
ing a mild oceanic climate. San Francisco tends to be slightly warmer, with aver
age temperatures ranging from 45?F to 67?F, and receives less rainfall, around 2
0 inches per year, mostly during winter. In contrast, Seattle is cooler, with te
mperatures ranging from 38?F to 64?F, and rainier, with around 37 inches of rain
fall per year, distributed throughout the year. San Francisco is also known for
its fog, particularly during summer, and receives more sunshine, around 160 sunn
y days per year, although it's often filtered through the fog. Overall, San Fran
cisco's weather is warmer and sunnier, with more pronounced seasonal variations,
while Seattle's is cooler and rainier, with more consistent temperatures throug
hout the year.
-- Call generate using the second conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
prompt => 'Explain the difference again in one paragraph only.',
profile_name => 'GENAI',
action => 'CHAT',
params => '{"conversation_id":"30C9DB6E-EA4E-AFBA-E063-9C6D46644B92"}') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
The cost of living in New York is approximately 20-30% higher than in Los Angele
s, mainly due to the higher cost of housing and transportation. New York has a m
edian home price of around $999,000 and average rent of $3,000 per month for a o
ne-bedroom apartment, compared to Los Angeles' median home price of $849,000 and
average rent of $2,400 per month. While the cost of food and utilities is relat
ively similar in both cities, the cost of transportation is higher in Los Angele
s due to its car-centric culture, but the cost of public transportation is highe
r in New York. Overall, the total monthly expenses for a single person in New Yo
rk can range from $4,600, compared to around $4,050 in Los Angeles, making New Y
ork the more expensive city to live in.
You may call the DBMS_CLOUD_AI.GENERATE function without specifying a conversation; however, in such cases, a meaningful response should not be expected.
-- Ask SELECT AI using the second conversation.
SELECT DBMS_CLOUD_AI.GENERATE(
prompt => 'Explain the difference again in one paragraph only.',
profile_name => 'GENAI',
action => 'CHAT') AS RESPONSE;
RESPONSE
--------------------------------------------------------------------------------
There is no previous explanation to draw from, as this is the beginning of our c
onversation. If you would like to ask a question or provide a topic, I would be
happy to explain the differences related to it in one paragraph.
You can query the DBMS_CLOUD_AI conversation views to review conversation and prompt details. See for more details.
Note:
TheViews with the DBA_ prefix are available only to users with administrator privileges (ADMIN).
SELECT conversation_id, conversation_title, description FROM dba_cloud_ai_conversations;
CONVERSATION_ID
------------------------------------
CONVERSATION_TITLE
----------------------------------------------------------------------------------------------------
DESCRIPTION
--------------------------------------------------------------------------------
30C9DB6E-EA4D-AFBA-E063-9C6D46644B92
Seattle vs San Francisco Weather
The conversation discusses the comparison of weather patterns between Seattle an
d San Francisco, focusing on the differences in temperature, rainfall, fog, suns
hine, and seasonal variation between the two cities.
30C9DB6E-EA4E-AFBA-E063-9C6D46644B92
NY vs LA Cost Comparison
The conversation discusses and compares the cost of living in New York and Los A
ngeles, covering housing, food, transportation, utilities, and taxes to provide
an overall view of the expenses in both cities.
SELECT conversation_id, count(*) FROM dba_cloud_ai_conversation_prompts
GROUP BY conversation_id;
CONVERSATION_ID COUNT(*)
------------------------------------ ----------
30C9DB6E-EA4D-AFBA-E063-9C6D46644B92 2
30C9DB6E-EA4E-AFBA-E063-9C6D46644B92 2You can update the title, description, and retention_days of a conversation using the DBMS_CLOUD_AI.UPDATE_CONVERSATION procedure. You can verify the update by querying the DBMS_CLOUD_AI conversation view.
-- Update the second conversation's title, description and retention_days
SQL> EXEC DBMS_CLOUD_AI.update_conversation(conversation_id => '30C9DB6E-EA4E-AFBA-E063-9C6D46644B92',
attributes => '{"retention_days":20,
"description":"This a description",
"title":"a title",
"conversation_length":20}');
PL/SQL procedure successfully completed.
-- Verify the information for the second conversation
SQL> SELECT conversation_title, description, retention_days
FROM dba_cloud_ai_conversations
WHERE conversation_id = '30C9DB6E-EA4E-AFBA-E063-9C6D46644B92';
CONVERSATION_TITLE DESCRIPTION RETENTION_DAYS LENGTH
-------------------------- ------------------------------------ -------------- --------------
a title This a description 20 20You can delete an individual prompt from your conversations and verify the modification by querying the DBMS_CLOUD_AI conversation view.
-- Find the latest prompt for first conversation
SELECT conversation_prompt_id FROM dba_cloud_ai_conversation_prompts
WHERE conversation_id = '30C9DB6E-EA4D-AFBA-E063-9C6D46644B92'
ORDER BY created DESC
FETCH FIRST ROW ONLY;
CONVERSATION_PROMPT_ID
------------------------------------
30C9DB6E-EA61-AFBA-E063-9C6D46644B92
-- Delete the prompt
EXEC DBMS_CLOUD_AI.DELETE_CONVERSATION_PROMPT('30C9DB6E-EA61-AFBA-E063-9C6D46644B92');
PL/SQL procedure successfully completed.
-- Verify if the prompt is deleted
SELECT conversation_prompt_id FROM dba_cloud_ai_conversation_prompts
WHERE conversation_id = '30C9DB6E-EA4D-AFBA-E063-9C6D46644B92';
-- Only one prompt now
CONVERSATION_PROMPT_ID
------------------------------------
30C9DB6E-EA5A-AFBA-E063-9C6D46644B92You can delete the entire conversation, which also removes all prompts associated with it.
-- Delete the first conversation
EXEC DBMS_CLOUD_AI.DROP_CONVERSATION('30C9DB6E-EA4D-AFBA-E063-9C6D46644B92');
PL/SQL procedure successfully completed.
-- Verify if the conversation and its prompts are removed
SELECT conversation_id FROM dba_cloud_ai_conversations;
-- We only have the second conversation now
CONVERSATION_ID
------------------------------------
30C9DB6E-EA4E-AFBA-E063-9C6D46644B92
SELECT conversation_id, count(*) FROM dba_cloud_ai_conversation_prompts GROUP BY conversation_id;
-- We only have prompts in the second conversation
CONVERSATION_ID COUNT(*)
------------------------------------ ----------
30C9DB6E-EA4E-AFBA-E063-9C6D46644B92 2Example: Select AI Feedback
These examples demonstrate how you can use the DBMS_CLOUD_AI.FEEDBACK procedure and the different scenarios for providing feedback to improve subsequent SQL query generation.
Note:
You can provide feedback for Select AI SQL prompts even if the prompt has not been run previously. Select AI does not require the SQL prompt to be used in a query before submitting feedback; you may supply feedback for any valid prompt at any time.
The following example demonstrates providing corrections to the generated SQL as feedback (negative feedback) using feedback_type as negative and providing your SQL query.
You add your feedback to the AI profile named OCI_FEEDBACK1 by calling the DBMS_CLOUD_AI.FEEDBACK procedure with the sql_text parameter containing the prompt. See to learn about the attributes. Then, you retrieve the content and attributes columns from the <profile_name>_FEEDBACK_VECINDEX$VECTAB table, which is linked to that specific SQL query. Select AI automatically creates this vector table when you first use the feedback feature. See for more information.
SQL> select ai showsql how many movies;
RESPONSE
------------------------------------------------------------------------
SELECT COUNT(m."MOVIE_ID") AS "Number of Movies" FROM "ADB_USER"."MOVIES" m
SQL> exec DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1', sql_text=> 'select ai showsql how many movies', feedback_type=> 'negative', response=>'SELECT SUM(1) FROM "ADB_USER"."MOVIES"');
PL/SQL procedure successfully completed.
SQL> select CONTENT, ATTRIBUTES from OCI_FEEDBACK1_FEEDBACK_VECINDEX$VECTAB where JSON_VALUE(attributes, '$.sql_text') = 'select ai showsql how many movies';
CONTENT
----------------------------------------------------------------------------------------------------
how many movies
ATTRIBUTES
----------------------------------------------------------------------------------------------------
{"response":"SELECT SUM(1) FROM \"ADB_USER\".\"MOVIES\"","feedback_type":"negative","sql_id":null,"sql_text":"select ai showsql how many movies","feedback_content":null}The following example demonstrates providing your approval that you agree and confirm the generated SQL (positive feedback) using feedback_type as positive.
In this example, the query retrieves the sql_id from the v$mapped_sql view for the given prompt. See V_MAPPED_SQL for more information.
You add your feedback to the AI profile named OCI_FEEDBACK1 by calling the DBMS_CLOUD_AI.FEEDBACK procedure with the sql_id parameter. Then, you retrieve the content and attributes columns from the <profile_name>_FEEDBACK_VECINDEX$VECTAB table, which is linked to that specific SQL query. Select AI automatically creates this vector table when you first use the feedback feature. See for more information.
SQL> select ai showsql how many distinct movie genres?;
RESPONSE
-----------------------------------------------------------------------------------------
SELECT COUNT(DISTINCT g."GENRE_NAME") AS "Number of Movie Genres" FROM "ADB_USER"."GENRES" g
SQL> SELECT sql_id FROM v$mapped_sql WHERE sql_text = 'select ai showsql how many distinct movie genres?';
SQL_ID
-------------
852w8u83gktc1
SQL> exec DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1', sql_id=> '852w8u83gktc1', feedback_type=>'positive', operation=>'add');
PL/SQL procedure successfully completed.
SQL> SELECT content, attributes FROM OCI_FEEDBACK1_FEEDBACK_VECINDEX$VECTAB WHERE JSON_VALUE(attributes, '$.sql_id') ='852w8u83gktc1';
CONTENT
----------------------------------------------------------------------------------------------------
how many distinct movie genres?
ATTRIBUTES
----------------------------------------------------------------------------------------------------
{"response":"SELECT COUNT(DISTINCT g.\"GENRE_NAME\") AS \"Number of Movie Genres\" FROM \"ADB_USER\".\"GENRES\" g","feedback_type":"positive","sql_id":"852w8u83gktc1","sql_text":"select ai showsql how many distinct movie genres?","feedback_content":null}You may provide feedback for SQL prompts even if the prompt has not been used previously. For example:
BEGIN
DBMS_CLOUD_AI.FEEDBACK(
profile_name=>'AI_PROFILE',
sql_text=>'select ai runsql how many products named PAD', -- Prior usage not required
feedback_type=>'negative',
response=>'SELECT COUNT(*) AS "Num" FROM "PRODUCTS"."CATG" o WHERE UPPER(o."NAME") LIKE ''%PAD%''',
feedback_content=>'Use LIKE instead of ='
);
END;
/In this case, feedback for the prompt select ai runsql how many products named PAD is submitted without needing to use the prompt beforehand.
DBMS_CLOUD_AI.FEEDBACK procedure parameters. This example demonstrates using sql_id and sql_text along with other parameters.
Note:
Select AI allows only a single feedback entry for eachsql_id. If you provide additional feedback for the same sql_id, Select AI replaces the previous entry with the new one.
See for more details on the parameters.
EXEC DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1',
sql_id=> '852w8u83gktc1',
feedback_type=>'positive',
operation=>'add');
EXEC DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1',
sql_text=> 'select ai showsql how many movies',
feedback_type=> 'negative',
response=>'SELECT SUM(1) FROM "ADB_USER"."MOVIES"',
feedback_content=>'Use SUM instead of COUNT');
EXEC DBMS_CLOUD_AI.FEEDBACK(profile_name=>'OCI_FEEDBACK1',
sql_id=> '852w8u83gktc1',
operation=>'delete');This example demonstrates using feedback action to improve the generated SQL by suggesting the modifications using natural language.
BEGIN
DBMS_CLOUD_AI.CREATE_PROFILE(
profile_name=>'OCI_FEEDBACK1',
attributes=>'{"provider": "oci",
"credential_name": "GENAI_CRED",
"oci_compartment_id": "ocid1.compartment.oc1..aaaa...",
"object_list": [{"owner": "ADB_USER", "name": "users"},
{"owner": "ADB_USER", "name": "movies"},
{"owner": "ADB_USER", "name": "genres"},
{"owner": "ADB_USER", "name": "watch_history"},
{"owner": "ADB_USER", "name": "movie_genres"},
{"owner": "ADB_USER", "name": "employees1"},
{"owner": "ADB_USER", "name": "employees2"}
]
}');
END;
/
EXEC DBMS_CLOUD_AI.SET_PROFILE('OCI_FEEDBACK1');
PL/SQL procedure successfully completed.
select ai showsql rank movie duration;
RESPONSE
-------------------------------------------------------------------------------
SELECT "DURATION" AS "Movie Duration" FROM "ADB_USER"."MOVIES" ORDER BY "DURATION"
select ai feedback use ascending sorting;
RESPONSE
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Based on your feedback, the SQL query for prompt "rank movie duration" is successfully refined. The refined SQL query as following:
SELECT m."DURATION" AS "Movie Duration" FROM "ADB_USER."MOVIES" m ORDER BY m."DURATION" ASC
select ai showsql rank the movie duration;
RESPONSE
-----------------------------------------------------------------------------------------
SELECT m."DURATION" AS "Movie Duration" FROM "ADB_USER."MOVIES" m ORDER BY m."DURATION" ASCThis example demonstrates using the feedback action to accept the generated SQL using natural language.
--Positive feedback
select ai showsql which movies are comedy?;
RESPONSE
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT DISTINCT m."TITLE" AS "Movie Title" FROM "ADB_USER"."MOVIES" m INNER JOIN "ADB_USER"."MOVIE_GENRES" mg ON m."MOVIE_ID" = mg."MOVIE_ID" INNER JOIN "ADB_USER"."GENRES" g ON mg."GENRE_ID" = g."GENRE_ID" WHERE g."GENRE_NAME" = 'comedy'
select ai feedback this is correct;
RESPONSE
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Thank you for your positive feedback. The SQL query for prompt "which movies are comedy?" is correctly implemented and delivering the expected results. It will be referenced for future optimizations and improvements.
Select AI Feedback Action Referring SQL_IDThis example demonstrates using SQL_ID with the feedback action to provide feedback for a particular generated SQL query. You can obtain the SQL_ID by querying the v$MAPPED_SQL table.
-- Query mentioned with SQL_ID
select ai showsql how many movies are in each genre;
RESPONSE
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT g."GENRE_NAME" AS "Genre Name", COUNT(m."MOVIE_ID") AS "Number of Movies" FROM "ADB_USER"."MOVIES" m INNER JOIN "ADB_USER"."MOVIE_GENRES" mg ON m."MOVIE_ID" = mg."MOVIE_ID" INNER JOIN "ADB_USER"."GENRES" g ON mg."GENRE_ID" = g."GENRE_ID" GROUP BY g."GENRE_NAME"
select sql_id from v$cloud_ai_sql where sql_text = 'select ai showsql how many movies are in each genre';
SQL_ID
-------------
8azkwc0hr87ga
select ai feedback for query with sql_id = '8azkwc0hr87ga', rank in descending sorting;
RESPONSE
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Based on your feedback, the SQL query for prompt "how many movies are in each genre" is successfully refined. The refined SQL query as following:
SELECT g."GENRE_NAME" AS "Genre Name", COUNT(m."MOVIE_ID") AS "Number of Movies"
FROM "ADB_USER"."MOVIES" m
INNER JOIN "ADB_USER"."MOVIE_GENRES" mg ON m."MOVIE_ID" = mg."MOVIE_ID"
INNER JOIN "ADB_USER"."GENRES" g ON mg."GENRE_ID" = g."GENRE_ID"
GROUP BY g."GENRE_NAME"
ORDER BY COUNT(m."MOVIE_ID") DESC
This example shows the feedback action for a specific Select AI query by including the Select AI prompt in quotes followed by your feedback.
-Query mentioned with SQL_TEXT
select ai showsql how many watch history in total;
RESPONSE
----------------------------------------------------------------------------------
SELECT COUNT(w."WATCH_ID") AS "Total Watch History" FROM "ADB_USER"."WATCH_HISTORY" w
select ai feedback for query "select ai showsql how many watch history in total", name the column as total_watch;
RESPONSE
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Based on your feedback, the SQL query for prompt "how many watch history in total" is successfully refined. The refined SQL query as following:
SELECT COUNT(w."WATCH_ID") AS "total_watch" FROM "ADB_USER"."WATCH_HISTORY" wExample: Select AI for Property Graphs
This example shows how you can use the DBMS_CLOUD_AI.GENERATE procedure and a natural language prompt to generate PGQ graph queries to query graph data.
This example shows how to define multiple property graphs in your AI profile, including a sample query and its output.
BEGIN
DBMS_CLOUD_AI.CREATE_PROFILE(
profile_name =>'OPENAI',
attributes =>'{"provider": "openai",
"model": "gpt-4o",
"credential_name": "OPENAI_CRED",
"object_list": [{"owner": "ADB_USER", "name": "LDBC_GRAPH"},
{"owner": "ADB_USER", "name": "G"}]
}');
END;
/
SQL> EXEC DBMS_CLOUD_AI.SET_PROFILE(profile_name => 'OPENAI');
PL/SQL procedure successfully completed.
SQL> select ai who bought a dress;
CUSTOMER_N
----------
Kate
1 row selected.Example: Sample Prompts for Property Graphs
These examples show how to create sample data and display the generated SQL using the showsql action for a given prompt.
The following example creates sample tables and a property graph.
CREATE TABLE Person
(
id NUMBER PRIMARY KEY,
firstName VARCHAR2(20 CHAR),
lastName VARCHAR2(20 CHAR),
age NUMBER,
jsonProp VARCHAR2(40 CHAR)
);
CREATE TABLE Post
(
id NUMBER PRIMARY KEY,
content VARCHAR2(20 CHAR)
);
CREATE TABLE personLikesPost
(
idPerson NUMBER REFERENCES Person (id),
idPost NUMBER REFERENCES Post (id)
);
CREATE TABLE personKnowsPerson
(
idPerson1 NUMBER REFERENCES Person (id),
idPerson2 NUMBER REFERENCES Person (id)
);
CREATE PROPERTY GRAPH person_graph
VERTEX TABLES (
Person KEY (id) LABEL Person
PROPERTIES (firstName, lastName, age, jsonProp),
Post KEY (id) LABEL Post
PROPERTIES(content)
)
EDGE TABLES (
personLikesPost
KEY(idPerson, idPost)
SOURCE KEY (idPerson) REFERENCES Person (id)
DESTINATION KEY (idPost) REFERENCES POST (id)
LABEL Likes NO PROPERTIES,
personKnowsPerson
KEY(idPerson1, idPerson2)
SOURCE KEY (idPerson1) REFERENCES Person (id)
DESTINATION KEY (idPerson2) REFERENCES Person (id)
LABEL Knows NO PROPERTIES
);
insert into Person values (1, 'John', 'Doe',23, '{"key1":"value1","key2":"value2"}');
insert into Person values (2, 'Scott', 'Tiger', 25, '{"key1":"value3","key2":"value4"}');
insert into Person values (3, 'Max', 'Power', 27, '{"key1":"value5","key2":"value6"}');
insert into Person values (4, 'Jane', 'Doe', 22, '{"key1":"value7","key2":"value8"}');
insert into Person (id, Firstname, age) values (5, 'Hans', 23);
insert into Person (id, Firstname, age) values (6, 'Franz', 24);
INSERT INTO Post VALUES (10, 'Lorem ipsum...');
INSERT INTO Post VALUES (11, 'Nulla facilisi...');
INSERT INTO Post VALUES (12, 'Vestibulum eget ..');
INSERT INTO Post VALUES (13, 'Sed fermentum...');
INSERT INTO Post VALUES (14, 'Fusce at ...');
INSERT INTO Post VALUES (15, 'Pellentesque sit ...');
INSERT INTO Post VALUES (16, 'Integer...');
INSERT INTO Post VALUES (17, 'Curabitur luctus ...');
INSERT INTO Post VALUES (18, 'Nam in ...');
INSERT INTO Post VALUES (19, 'Etiam ac ...');
insert into personKnowsPerson values (1, 2);
insert into personKnowsPerson values (2, 3);
insert into personKnowsPerson values (3, 4);
insert into personKnowsPerson values (4, 5);
insert into personKnowsPerson values (5, 6);
insert into personKnowsPerson values (6, 2);
insert into personKnowsPerson values (5, 3);
INSERT INTO personLikesPost VALUES (1, 10);
INSERT INTO personLikesPost VALUES (1, 11);
INSERT INTO personLikesPost VALUES (1, 12);
INSERT INTO personLikesPost VALUES (2, 10);
INSERT INTO personLikesPost VALUES (2, 13);
INSERT INTO personLikesPost VALUES (2, 14);
INSERT INTO personLikesPost VALUES (3, 11);
INSERT INTO personLikesPost VALUES (3, 15);
INSERT INTO personLikesPost VALUES (3, 16);
INSERT INTO personLikesPost VALUES (4, 12);
INSERT INTO personLikesPost VALUES (4, 17);
INSERT INTO personLikesPost VALUES (4, 18);
INSERT INTO personLikesPost VALUES (5, 13);
INSERT INTO personLikesPost VALUES (5, 14);
INSERT INTO personLikesPost VALUES (5, 19);
INSERT INTO personLikesPost VALUES (6, 15);
INSERT INTO personLikesPost VALUES (6, 16);
INSERT INTO personLikesPost VALUES (6, 17);
INSERT INTO personLikesPost VALUES (1, 18);
INSERT INTO personLikesPost VALUES (2, 19);
commit;Prompt: Find all the people IDs
SELECT person_id
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (v IS "PERSON")
COLUMNS (VERTEX_ID(v) AS person_id))Prompt: Find all the edge IDs
SELECT edge_id
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (v1) -[e]-> (v2)
COLUMNS (EDGE_ID(e) AS edge_id))Prompt: Find all the knows relationship IDs
SELECT knows_id
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p1 IS "PERSON") -[e IS "KNOWS"]-> (p2 IS "PERSON")
COLUMNS (EDGE_ID(e) AS knows_id))Prompt: List all people who know someone who liked the post 'Sed fermentum...'
SELECT person_id, person_firstname, person_lastname
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p1 IS "PERSON") -[e1 IS "KNOWS"]-> (p2 IS "PERSON") -[e2 IS "LIKES"]-> (post IS "POST")
WHERE UPPER(post."CONTENT") = UPPER('Sed fermentum...')
COLUMNS (VERTEX_ID(p1) AS person_id, p1."FIRSTNAME" AS person_firstname, p1."LASTNAME" AS person_lastname))Prompt: Find first name and last name of all people
SELECT first_name, last_name
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p IS "PERSON")
COLUMNS (p."FIRSTNAME" AS first_name, p."LASTNAME" AS last_name))Prompt: Find post contents liked by John Doe
SELECT post_content
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p IS "PERSON") -[e IS "LIKES"]-> (post IS "POST")
WHERE UPPER(p."FIRSTNAME") = UPPER('John') AND UPPER(p."LASTNAME") = UPPER('Doe')
COLUMNS (post."CONTENT" AS post_content))Prompt: Show all people (full name) and display their key1 value from jsonProp property
SELECT person_fullname, json_key1
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p IS "PERSON")
COLUMNS (
(p."FIRSTNAME" || ' ' || p."LASTNAME") AS person_fullname,
JSON_QUERY(p."JSONPROP", '$.key1') AS json_key1
)
)Prompt: Find friends of Scott Tiger ordered by their last name
SELECT friend_firstname, friend_lastname
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p IS "PERSON") -[e IS "KNOWS"]-> (f IS "PERSON")
WHERE UPPER(p."FIRSTNAME") = UPPER('Scott') AND UPPER(p."LASTNAME") = UPPER('Tiger')
COLUMNS (f."FIRSTNAME" AS friend_firstname, f."LASTNAME" AS friend_lastname)
)
ORDER BY friend_lastnamePrompt: Find all people ordered by first name. Skip one result and return 2 results only
SELECT person_firstname
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p IS "PERSON")
COLUMNS (p."FIRSTNAME" AS person_firstname))
ORDER BY person_firstname
OFFSET 1 ROWS FETCH NEXT 2 ROWS ONLYUnsupported Queries
For the following queries certain LLMs generate valid NL2SQL, but the resulting SQL uses features that are not yet supported in Oracle AI Database 26ai.
Prompt: Find people that do not know Scott.
EXISTS subquery is not supported.
SELECT person_id, first_name, last_name
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p1 IS "PERSON")
WHERE NOT EXISTS (
SELECT 1
FROM GRAPH_TABLE("ADB_USER"."PERSONGRAPH"
MATCH (p2 IS "PERSON") -[e IS "PERSONKNOWSPERSON"]-> (p3 IS "PERSON"
)
WHERE p2."ID" = p1."ID" AND UPPER(p3."FIRSTNAME") = UPPER('Scott')
COLUMNS (1 AS dummy_value))
)
COLUMNS (p1."ID" AS person_id, p1."FIRSTNAME" AS first_name, p1."LASTNAME" A
S last_name))Prompt: Show all people and how many posts they have liked (show people even if they have not liked a post).
OPTIONAL match is not supported.
SELECT person_id, person_firstname, person_lastname, liked_post_ids
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (p is "PERSON") OPTIONAL MATCH (p) -[l is "PERSONLIKESPOST"]-> (post is "POST")
COLUMNS(
VERTEX_ID(p) as person_id,
p."FIRSTNAME" as person_firstname,
p."LASTNAME" as person_lastname,
JSON_ARRAYAGG(VERTEX_ID(post)) as liked_post_ids
))Prompt: Find all people that Scott can reach.
Queries that use unbounded quantifiers are not supported.
SELECT person_id, person_firstname, person_lastname
FROM GRAPH_TABLE("ADB_USER"."PERSONGRAPH"
MATCH (src IS "PERSON") -[e IS "PERSONKNOWSPERSON"]->* (dst IS "PERSON")
WHERE src."FIRSTNAME" = 'Scott'
COLUMNS (
VERTEX_ID(dst) AS person_id,
dst."FIRSTNAME" AS person_firstname,
dst."LASTNAME" AS person_lastname
)
)Intermittent Queries
LLMs have been shown to struggle when translating queries that require more than one GRAPH_TABLE operator. The following are such examples:
Prompt: Show people who have liked all the same posts as Hans
SELECT person_id, person_name
FROM GRAPH_TABLE("PERSON_GRAPH"
MATCH (hans is "PERSON") -[likes_hans is "PERSONLIKESPOST"]-> (post is "POST"),
(other_person is "PERSON") -[likes_other is "PERSONLIKESPOST"]-> (post)
WHERE hans."FIRSTNAME" = 'Hans'
COLUMNS (VERTEX_ID(other_person) as person_id, other_person."FIRSTNAME" AS person_name)
)
WHERE NOT EXISTS (
SELECT 1
FROM GRAPH_TABLE("PERSONGRAPH"
MATCH (hans is "PERSON") -[likes_hans is "PERSONLIKESPOST"]-> (post is "POST")
WHERE hans."FIRSTNAME" = 'Hans'
COLUMNS (VERTEX_ID(post) as post_id)
) hans_posts
LEFT JOIN GRAPH_TABLE("PERSONGRAPH"
MATCH (other_person is "PERSON") -[likes_other is "PERSONLIKESPOST"]-> (post
is "POST")
COLUMNS (VERTEX_ID(post) as post_id)
) other_posts
ON hans_posts.post_id = other_posts.post_id
WHERE other_posts.post_id IS NULL
)Prompt: Find all names of the people that can be reached in a 1 to 3 edge path
SELECT person_name
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (start_person IS "PERSON") -[e IS "KNOWS"]->{1,3} (end_person IS "PERSON")
COLUMNS (end_person."FIRSTNAME" AS person_name))Prompt: Find all names of the people that can be reached in a 1 to 3 edge path where each person is younger than the next one
SELECT person_name
FROM GRAPH_TABLE("ADB_USER"."PERSON_GRAPH"
MATCH (start_person IS "PERSON") ((v1 IS "PERSON") -[e IS "KNOWS"]-> (v2 IS"PERSON") WHERE v1."AGE" < v2."AGE"){1,3} (end_person IS "PERSON")
COLUMNS (end_person."FIRSTNAME" AS person_name))LLMs often struggle with translating queries that require grouping and aggregation. A common mistake is placing aggregations in the COLUMNS clause instead of the SELECT clause.
Prompt: Find the average number of posts liked by all the users
SELECT AVG(COUNT(post)) AS average_liked_count
FROM GRAPH_TABLE("PERSON_GRAPH"
MATCH (p IS "PERSON") -[e IS "PERSONLIKESPOST"]-> (post IS "POST")
COLUMNS (VERTEX_ID(p) AS person, VERTEX_ID(post) AS post))
GROUP BY person;