Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En este documento, se describe cómo puedes usar Gemini, un colaborador potenciado por IA enGoogle Cloud, para ayudarte a hacer lo siguiente en AlloyDB para PostgreSQL:
Este documento está dirigido a ingenieros y administradores de bases de datos que estén familiarizados con AlloyDB y tengan cierto conocimiento de SQL y análisis de datos. Si es la primera vez que usas AlloyDB, consulta la descripción general de AlloyDB.
Después de crear la tabla Singers, haz clic en actualizarActualizar para actualizar el esquema de la base de datos.
Para inhabilitar las funciones de Gemini en AlloyDB, repite este paso y, luego, anula la selección de las funciones de Gemini que deseas inhabilitar.
Roles y permisos requeridos
Para usar Gemini con AlloyDB, necesitas los siguientes permisos:
alloydb.clusters.get
alloydb.databases.list
alloydb.instances.executeSql
alloydb.instances.list
alloydb.users.list
Puedes obtener este permiso a través del rol de roles/alloydb.admin. Si no tienes esta función, comunícate con el administrador de tu organización para solicitar acceso. También puedes obtener los permisos necesarios a través de roles personalizados o cualquier otro rol predefinido.
Genera consultas en SQL con instrucciones escritas en lenguaje natural
Puedes escribirle comentarios en lenguaje natural a Gemini (o instrucciones) para generar consultas basadas en tu esquema. Por ejemplo, puedes pedirle a Gemini que genere SQL al responder los siguientes mensajes:
“Crea una tabla que haga un seguimiento de los resultados de la encuesta de satisfacción del cliente”.
"Agrega una columna de fecha llamada cumpleaños a la tabla Singers".
"¿Cuántos cantantes nacieron en los 90?"
Si tu esquema cambia, como la adición de una tabla o columna nueva, debes hacer clic en actualizarActualizar para actualizar tu esquema antes de usar Gemini.
Para generar código SQL en AlloyDB con la ayuda de Gemini, sigue estos pasos:
En la Google Cloud consola, abre la página AlloyDB.
Para continuar con el ejemplo con la tabla Singers, si ingresas el mensaje -- show all singers born in the 70s, Gemini genera un SQL similar al siguiente:
Revisa la sugerencia de SQL y realiza cualquiera de las siguientes acciones:
Para ver las opciones para aceptar el SQL que genera Gemini, mantén el puntero sobre la consulta. Se muestran las siguientes opciones:
Aceptar: Para aceptar la consulta sugerida, presiona Tab y, luego, haz clic en Ejecutar.
Aceptar palabra: Para aceptar la consulta sugerida de forma parcial, presiona Control+Right arrow (o Command+Right arrow en macOS) y, luego, haz clic en Ejecutar.
Para editar el SQL original, presiona Tab, edita el SQL y, luego, haz clic en Ejecutar.
Para descartar una sugerencia, presiona EscEsc o continúa escribiendo.
Herramienta Help me code
Para usar la herramienta Help me code, sigue estos pasos:
En la Google Cloud consola, abre la página AlloyDB.
Revisa la consulta en SQL generada y realiza cualquiera de las siguientes acciones:
Para aceptar el SQL que genera Gemini, haz clic en Insertar
para insertar la declaración en el editor de consultas. Luego, haz clic en Ejecutar para ejecutar el SQL sugerido.
Para pedirle a Gemini que genere una consulta nueva, haz clic en Editar.
Después de editar el mensaje, haz clic en Actualizar. Luego, puedes decidir aceptar la nueva declaración generada o descartar la sugerencia.
Para descartar la sugerencia, cierra la ventana Help me code.
Explica instrucciones de SQL en el editor de consultas
Puedes ingresar consultas en lenguaje natural para solicitar explicaciones de las consultas de SQL.
Estas explicaciones pueden ayudarte a comprender la sintaxis, el esquema subyacente y el contexto empresarial para consultas complejas o largas.
En la Google Cloud consola, abre la página AlloyDB.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eGemini, an AI-powered tool in Google Cloud, can assist in AlloyDB for PostgreSQL by generating SQL queries from natural language prompts.\u003c/p\u003e\n"],["\u003cp\u003eUsers can leverage Gemini to complete SQL queries within the query editor by providing code completion suggestions based on the database schema.\u003c/p\u003e\n"],["\u003cp\u003eGemini allows users to obtain natural language explanations for complex or lengthy SQL queries, aiding in understanding syntax and context.\u003c/p\u003e\n"],["\u003cp\u003eUtilizing Gemini features requires specific permissions, such as \u003ccode\u003ealloydb.clusters.get\u003c/code\u003e, \u003ccode\u003ealloydb.databases.list\u003c/code\u003e, and others, often granted through the \u003ccode\u003eroles/alloydb.admin\u003c/code\u003e role.\u003c/p\u003e\n"],["\u003cp\u003eGemini is currently part of Gemini Code Assist and available at no charge until included in Gemini Code Assist Standard edition, at which point a license will be required.\u003c/p\u003e\n"]]],[],null,["# Write SQL with Gemini assistance\n\n| **Preview**\n|\n| This product is covered by the [Pre-GA Offerings Terms](/terms/service-terms#0)\n| of the Google Cloud Terms of Service. Pre-GA products might have limited support,\n| and changes to pre-GA products might not be compatible with other pre-GA versions.\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n\n\u003cbr /\u003e\n\nThis document describes how you can use\n[Gemini](/gemini/docs/overview), an AI-powered collaborator in\nGoogle Cloud, to help you do the following in AlloyDB for PostgreSQL:\n\n- [Generate SQL queries using natural language prompts.](#generate-sql-queries-using-natural-language-prompts)\n- [Explain SQL queries in the query editor.](#explain-sql-in-query-editor)\n\nLearn [how and when Gemini\nfor Google Cloud uses your data](/gemini/docs/discover/data-governance).\n\nThis document is intended for database administrators and data engineers who\nare familiar with AlloyDB, and somewhat familiar with SQL\nand data analysis. If you're new to AlloyDB, see\n[AlloyDB overview](/alloydb/docs/overview).\n| **Note** : Coding assistance is part of Gemini Code Assist and is available at no charge until it's included in Gemini Code Assist Standard edition. This change will be communicated at a later date. At that time, you will need to acquire a [Gemini Code Assist Standard edition license](/gemini/docs/discover/set-up-gemini#purchase-subscription) to continue to use coding assistance in AlloyDB for PostgreSQL Studio.\n\nBefore you begin\n----------------\n\n1. [Ensure that Gemini Cloud Assist is set up for your Google Cloud user account and project](/gemini/docs/cloud-assist/set-up-gemini).\n\n2. Optional: If you want to follow along with the examples in this document,\n create the `Singers` table using the following schema:\n\n CREATE TABLE Singers (\n BirthDate TIMESTAMPTZ,\n SingerId BIGINT PRIMARY KEY,\n FirstName VARCHAR(1024),\n LastName VARCHAR(1024),\n SingerInfo BYTEA\n );\n\n After you create the `Singers` table, click\n refresh**Refresh** to\n update your database schema.\n\nTo disable Gemini features in AlloyDB, repeat\nthis step, and then deselect the Gemini features that you want\nto disable.\n\n### Required roles and permissions\n\n\n| **Caution:** Users with broad database access could experience data loss when using Gemini. We recommend that you use an account with fewer database privileges when using Gemini.\n\n\u003cbr /\u003e\n\nTo use Gemini with AlloyDB, you need the following permissions:\n\n- `alloydb.clusters.get`\n- `alloydb.databases.list`\n- `alloydb.instances.executeSql`\n- `alloydb.instances.list`\n- `alloydb.users.list`\n\nYou can get this permission through the\n[`roles/alloydb.admin`](/alloydb/docs/reference/iam-roles-permissions#roles)\nrole. If you don't have this role, contact your Organization Administrator to\nrequest access. You might also be able to get the required permissions through\n[custom roles](/iam/docs/creating-custom-roles) or\nother [predefined roles](/iam/docs/understanding-roles).\n\nAdditionally, ensure that\nyou have [database-level permissions](/alloydb/docs/database-users/about)\nfor the database that you're using for authentication.\n\nGenerate SQL queries using natural language prompts\n---------------------------------------------------\n\n| As an early-stage technology, Gemini for Google Cloud\n| products can generate output that seems plausible but is factually incorrect. We recommend that you\n| validate all output from Gemini for Google Cloud products before you use it.\n| For more information, see\n| [Gemini for Google Cloud and responsible AI](/gemini/docs/discover/responsible-ai).\n\nYou can give Gemini natural language comments (or *prompts*) to\ngenerate queries that are based on your schema. For example, you can prompt\nGemini to generate SQL in response to the following prompts:\n\n- \"Create a table that tracks customer satisfaction survey results.\"\n- \"Add a date column called birthday to the Singers table.\"\n- \"How many singers were born in the 90s?\"\n\nIf your schema changes, such as addition of a new table or column, then you\nmust click refresh**Refresh** to update\nyour schema before using Gemini.\n| **Note:** When you enter a prompt, information about your database's schema is included with the prompt. This can include table and column names, data types, and column descriptions. Your database schema and data remain in AlloyDB and aren't sent to Gemini.\n\nTo generate SQL in AlloyDB with Gemini\nassistance, follow these steps:\n\n1. In the Google Cloud console, open the **AlloyDB** page.\n\n [Go to AlloyDB](https://console.cloud.google.com/alloydb)\n2. Select a cluster from the list.\n\n3. In the navigation menu, click **AlloyDB**.\n\n4. Select a database and user, and enter the user's password.\n\n5. Click **Authenticate** . The **Explorer** pane displays a list of the objects in your database.\n\n6. To query your database, click the add\n **New SQL editor tab** . Make sure that\n [SQL generation is enabled](#before-you-begin).\n\n7. To generate SQL, type a comment in the query editor starting\n with `--` followed by a\n [single-line comment](/bigquery/docs/reference/standard-sql/lexical#comments),\n and then press \u003ckbd\u003eReturn\u003c/kbd\u003e.\n\n For example, if you enter the prompt `-- add a row to table singers` and\n press \u003ckbd\u003eReturn\u003c/kbd\u003e, then Gemini generates SQL that's\n similar to the following: \n\n INSERT INTO Singers (SingerId, FirstName, LastName, BirthDate)\n VALUES (1, Alex, 'M.', '1977-10-16');\n\n To continue the example using the `Singers` table, if you enter the\n prompt `-- show all singers born in the 70s`, then Gemini\n generates SQL that's similar to the following: \n\n SELECT *\n FROM Singers\n WHERE Singers.BirthDate\n BETWEEN '1970-01-01' AND '1979-12-31'\n\n | **Note:** Gemini might suggest different syntax each time that you enter the same prompt.\n8. Review the SQL suggestion and take any of the following actions:\n\n | **Caution:** Because Data Manipulation Language (DML) and Data Definition Language (DDL) queries generated by Gemini can overwrite data, we recommend that you validate the generated SQL queries before you run the queries.\n - To view the options for accepting the SQL generated by Gemini, hold the pointer over the query. The following options are displayed:\n - **Accept** : To accept the suggested query, press `Tab`, then click **Run**.\n - **Accept word** : To accept the suggested query partially, press `Control`+`Right arrow`. (or `Command`+`Right arrow` on macOS), then click **Run**.\n - To edit the original SQL, press `Tab`, edit the SQL, and then click **Run**.\n - To dismiss the suggestion, press `Esc` or continue typing.\n\n### Help me code tool\n\nTo use the **Help me code** tool, follow these steps:\n\n1. In the Google Cloud console, open the **AlloyDB** page.\n\n [Go to AlloyDB](https://console.cloud.google.com/alloydb)\n2. Select a cluster from the list.\n\n3. In the navigation menu, click **AlloyDB**.\n\n4. Select a database and user, and enter the user's password.\n\n5. Click **Authenticate** . The **Explorer** pane displays a list of the objects in your database.\n\n6. To query your database, click the add\n **New tab**.\n\n7. Click pen_spark\n **Help me code** next to the query editor.\n\n8. In the **Help me code** window, enter a prompt. For example, `add a row to\n table singers` and click **Generate**.\n\n Gemini generates SQL that's similar to the following: \n\n INSERT INTO Singers (SingerId, FirstName, LastName, BirthDate)\n VALUES (1, Alex, 'M.', '1977-10-16');\n\n | **Note:** Gemini might suggest different syntax each time that you enter the same prompt.\n9. Review the generated SQL and take any of the following actions:\n\n | **Caution:** Because Data Manipulation Language (DML) and Data Definition Language (DDL) queries generated by Gemini can overwrite data, we recommend that you validate the generated queries before you run the queries.\n - To accept SQL generated by Gemini, click **Insert** to insert the statement into the query editor. Then click **Run** to execute the suggested SQL.\n - To ask Gemini to generate a new query, click **Edit** . After you've edited your prompt, click **Update**. You can then decide to accept the new generated statement or dismiss the suggestion.\n - To dismiss the suggestion, close the **Help me code** window.\n\nExplain SQL statements in the query editor\n------------------------------------------\n\nYou can enter natural language queries to request explanations of SQL queries.\nThese explanations can help you understand the syntax,\nunderlying schema, and business context for complex or long queries.\n\n1. In the Google Cloud console, open the **AlloyDB** page.\n\n [Go to AlloyDB](https://console.cloud.google.com/alloydb)\n2. Select a cluster from the list.\n\n3. In the navigation menu, click **AlloyDB**.\n\n4. Select a database and user, and enter the user's password.\n\n5. Click **Authenticate** . The **Explorer** pane displays a list of the objects in your database.\n\n6. To query your database, click the add\n **New tab**.\n\n7. In the query editor, paste the query.\n\n8.\n Highlight the query that you want Gemini to explain, and\n then click pen_spark\n **Explain this query**.\n\n The SQL explanation appears in the Gemini **Chat** window.\n\nWhat's next\n-----------\n\n- Read [Gemini for Google Cloud overview](/gemini/docs/overview).\n- Learn [how Gemini uses your data](/gemini/docs/discover/data-governance).\n- Learn how to [analyze your data in Google Cloud using Gemini](/bigquery/docs/gemini-analyze-data)."]]