Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Ce document explique comment utiliser Gemini, un collaborateur optimisé par l'IA dansGoogle Cloud, pour vous aider à effectuer les opérations suivantes dans AlloyDB pour PostgreSQL :
Ce document est destiné aux administrateurs de bases de données et aux ingénieurs de données qui connaissent bien AlloyDB, et qui sont quelque peu familiarisés avec SQL et l'analyse de données. Si vous débutez avec AlloyDB, consultez la présentation d'AlloyDB.
Après avoir créé la table Singers, cliquez sur actualiserActualiser pour mettre à jour le schéma de votre base de données.
Pour désactiver les fonctionnalités Gemini dans AlloyDB, répétez cette étape, puis désélectionnez celles que vous souhaitez désactiver.
Rôles et autorisations requis
Pour utiliser Gemini avec AlloyDB, vous devez disposer des autorisations suivantes :
alloydb.clusters.get
alloydb.databases.list
alloydb.instances.executeSql
alloydb.instances.list
alloydb.users.list
Vous pouvez obtenir cette autorisation grâce au rôle roles/alloydb.admin. Si vous ne disposez pas de ce rôle, contactez l'administrateur de votre organisation pour demander l'accès. Vous pouvez également obtenir les autorisations requises grâce aux rôles personnalisés ou à d'autres rôles prédéfinis.
Générer des requêtes SQL à l'aide de requêtes en langage naturel
Vous pouvez envoyer des commentaires (ou des requêtes) Gemini en langage naturel pour générer des requêtes basées sur votre schéma. Par exemple, vous pouvez inviter Gemini à générer du code SQL en réponse aux requêtes suivantes :
"Créez une table qui suit les résultats de l'enquête de satisfaction client."
"Ajoutez une colonne de date appelée "Date de naissance" à la table "Chanteurs"."
"Combien de chanteurs sont nés dans les années 1990 ?"
Si votre schéma change, par exemple en ajoutant une nouvelle table ou une nouvelle colonne, vous devez cliquer sur actualiserActualiser pour mettre à jour votre schéma avant d'utiliser Gemini.
Pour générer du code SQL dans AlloyDB avec l'assistance de Gemini, procédez comme suit :
Dans la console Google Cloud , ouvrez la page AlloyDB.
Sélectionnez une base de données et un utilisateur, puis saisissez le mot de passe de l'utilisateur.
Cliquez sur Authentifier. Le volet Explorateur affiche la liste des objets de votre base de données.
Pour interroger votre base de données, cliquez sur addNouvel onglet de l'éditeur SQL. Assurez-vous que la génération de code SQL est activée.
Pour générer du code SQL, saisissez un commentaire dans l'éditeur de requête commençant par -- suivi d'un commentaire sur une seule ligne, puis appuyez sur Retour.
Par exemple, si vous saisissez la requête -- add a row to table singers et appuyez sur Entrée, Gemini génère un code SQL semblable à celui-ci :
Pour continuer l'exemple à l'aide de la table Singers, si vous saisissez la requête -- show all singers born in the 70s, Gemini génère un code SQL semblable à celui-ci :
Examinez la suggestion SQL et effectuez l'une des actions suivantes :
Pour afficher les options permettant d'accepter le code SQL généré par Gemini, maintenez le pointeur sur la requête. Les options suivantes s'affichent :
Accepter : pour accepter la requête suggérée, appuyez sur Tab, puis cliquez sur Exécuter.
Accepter le mot : pour accepter partiellement la requête suggérée, appuyez sur Control+Right arrow (ou Command+Right arrow sous macOS), puis cliquez sur Exécuter.
Pour modifier le code SQL d'origine, appuyez sur Tab, modifiez le code SQL, puis cliquez sur Exécuter.
Pour ignorer la suggestion, appuyez sur Esc ou poursuivez la saisie.
Outil "m'aider à coder"
Pour utiliser l'outil M'aider à coder, procédez comme suit :
Dans la console Google Cloud , ouvrez la page AlloyDB.
Examinez le code SQL généré et effectuez l'une des actions suivantes :
Pour accepter le code SQL généré par Gemini, cliquez sur Insérer pour insérer l'instruction dans l'éditeur de requête. Cliquez ensuite sur Exécuter pour exécuter le code SQL suggéré.
Pour demander à Gemini de générer une nouvelle requête, cliquez sur Modifier.
Une fois que vous avez modifié votre invite de commande, cliquez sur Mettre à jour. Vous pouvez ensuite décider d'accepter la nouvelle instruction générée ou d'ignorer la suggestion.
Pour ignorer la suggestion, fermez la fenêtre M'aider à coder.
Expliquer des instructions SQL dans l'éditeur de requête
Vous pouvez saisir des requêtes en langage naturel pour demander des explications sur les requêtes SQL.
Ces explications peuvent vous aider à comprendre la syntaxe, le schéma sous-jacent et le contexte commercial des requêtes complexes ou longues.
Dans la console Google Cloud , ouvrez la page AlloyDB.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 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)."]]