{"id":29071,"date":"2024-05-03T05:44:22","date_gmt":"2024-05-03T04:44:22","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/domina-mysql-uso-de-select-into-para-almacenar-variables\/"},"modified":"2024-06-03T17:44:14","modified_gmt":"2024-06-03T16:44:14","slug":"domina-mysql-uso-de-select-into-para-almacenar-variables","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/master-mysql-using-select-into-to-store-variables\/","title":{"rendered":"Master MySQL: Using SELECT INTO to Store Variables"},"content":{"rendered":"<p>MySQL is a powerful tool for database management, and one of its most useful features is the SELECT INTO command, which allows you to store the results of a query directly in local variables. In this tutorial, we will explore how you can implement this technique to optimize your SQL scripts and make your databases more dynamic and efficient.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-mysql-using-select-into-to-store-variables\/#%C2%BFQue_es_SELECT_INTO\" >What is SELECT INTO?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-mysql-using-select-into-to-store-variables\/#Utilizar_SELECT_INTO_en_MySQL\" >Use SELECT INTO in MySQL<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-mysql-using-select-into-to-store-variables\/#Casos_de_uso_comunes\" >Common use cases<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-mysql-using-select-into-to-store-variables\/#Buenas_practicas_al_usar_SELECT_INTO\" >Good practices when using SELECT INTO<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-mysql-using-select-into-to-store-variables\/#Ejemplos_practicos\" >Practical examples<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-mysql-using-select-into-to-store-variables\/#Ejemplo_1_Almacenar_multiples_valores\" >Example 1: Store multiple values<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-mysql-using-select-into-to-store-variables\/#Ejemplo_2_Uso_en_procedimientos_para_decisiones_de_flujo\" >Example 2: Use in procedures for flow decisions<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-mysql-using-select-into-to-store-variables\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"%C2%BFQue_es_SELECT_INTO\"><\/span>What is SELECT INTO?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>SELECT INTO is a statement in SQL that is used to select data from a table and assign those values directly to predefined variables in a programming environment. This command is especially useful in stored procedures, where it can simplify data handling and facilitate procedures such as validating or transforming data before use. <\/p>\n<h2><span class=\"ez-toc-section\" id=\"Utilizar_SELECT_INTO_en_MySQL\"><\/span>Use SELECT INTO in MySQL<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>To start using SELECT INTO in MySQL, you first need to define the variables where you will store the results. Let&#039;s see it with a practical example:<\/p>\n<pre><code class=\"&quot;language-sql&quot;\">DECLARE customerName VARCHAR(255); DECLARE totalPurchases DECIMAL(10,2); SELECT name, total INTO customerName, totalPurchases FROM customers WHERE customer_id = 101;<\/code><\/pre>\n<p>In this case, we select the name and purchase total of a specific customer and store those values in the variables <code>client name<\/code> y <code>totalShopping<\/code>. This allows us to use those values in subsequent operations or conditions within the same stored procedure.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Casos_de_uso_comunes\"><\/span>Common use cases<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<ol>\n<li>\n<p><strong>Custom reports:<\/strong> You can use SELECT INTO to generate specific data for a report, storing results in variables that are then used to construct the content of the report.<\/p>\n<\/li>\n<li>\n<p><strong>Validations:<\/strong> Before performing complex operations or inserting new data, you can capture existing values in variables to facilitate necessary checks and validations.<\/p>\n<\/li>\n<li>\n<p><strong>Flow control:<\/strong> In stored procedures, you can redirect the flow of the script based on the values stored in the variables, allowing you to create more complex and efficient logic.<\/p>\n<\/li>\n<\/ol>\n<h2><span class=\"ez-toc-section\" id=\"Buenas_practicas_al_usar_SELECT_INTO\"><\/span>Good practices when using SELECT INTO<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>When using SELECT INTO, it is important to follow some good practices to ensure code performance and maintainability:<\/p>\n<ul>\n<li>\n<p><strong>Avoid excessive use:<\/strong> Although it is a powerful tool, overuse of SELECT INTO can lead to code that is difficult to maintain and debug. Use it when it really adds clarity or efficiency to the script.<\/p>\n<\/li>\n<li>\n<p><strong>Handling of NULLs:<\/strong> Be sure to consider what should happen if the query does not return a value. MySQL allows you to set default values or perform specific actions in case of NULL.<\/p>\n<\/li>\n<li>\n<p><strong>Query Optimization:<\/strong> Since SELECT INTO can require access to multiple rows and columns, make sure your queries are optimized, using appropriate indexes and clear WHERE conditions to limit the data processed.<\/p>\n<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Ejemplos_practicos\"><\/span>Practical examples<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Now, let&#039;s look at some more practical examples of how to implement SELECT INTO in different scenarios:<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Ejemplo_1_Almacenar_multiples_valores\"><\/span>Example 1: Store multiple values<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<pre><code class=\"&quot;language-sql&quot;\">DECLARE maximumsale DECIMAL(10,2); DECLARE sellerTop VARCHAR(255); -- Obtaining the maximum sales and the corresponding salesperson SELECT MAX(sale_total), salesperson_name INTO maximumsale, topseller FROM sales JOIN salespeople ON sales.salesperson_id = salespeople.id WHERE sales_date BETWEEN &#039;2023-01-01&#039; AND &#039;2023-01-31&#039;;<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Ejemplo_2_Uso_en_procedimientos_para_decisiones_de_flujo\"><\/span>Example 2: Use in procedures for flow decisions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<pre><code class=\"&quot;language-sql&quot;\">CREATE PROCEDURE CheckCustomerImportant(IN customerId INT) BEGIN DECLARE totalPurchased DECIMAL(10,2); SELECT SUM(total) INTO totalPurchased FROM purchases WHERE customer_id = customerId; total IFPurchased &gt; 10000 THEN -- Actions for important clients ELSE -- Actions for regular clients END IF; END;<\/code><\/pre>\n<p>These examples show the flexibility and power of using SELECT INTO in MySQL. By storing results directly in variables, developers can create more robust and maintainable database applications.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The SELECT INTO command is a very useful feature in MySQL that, when used correctly, can significantly improve the efficiency and clarity of your stored procedures and SQL scripts. As we have seen, its applications can range from simple data storage to the advanced manipulation required in complex business logic.<\/p>\n<p>To explore more about SQL and other database functionalities, I invite you to visit and explore <a href=\"https:\/\/nelkodev.com\/en\/\">NelkoDev<\/a>. And if you have specific questions or need help with your projects, feel free to contact me via <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">https:\/\/nelkodev.com\/contacto<\/a>. Keep learning and improving your data management skills with MySQL!<\/p>","protected":false},"excerpt":{"rendered":"<p>MySQL es una herramienta potente en el manejo de bases de datos, y una de sus funcionalidades m\u00e1s \u00fatiles es el comando SELECT INTO, el cual permite almacenar los resultados de una consulta directamente en variables locales. En este tutorial, exploraremos c\u00f3mo puedes implementar esta t\u00e9cnica para optimizar tus scripts de SQL y hacer tus [&hellip;]<\/p>","protected":false},"author":1,"featured_media":29072,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420,2185],"tags":[1886,9,205,2013,2189,1473,2200,624,2121,352,60,935,512,791],"class_list":["post-29071","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-curso-mysql","tag-almacenar","tag-base-de-datos","tag-blog","tag-csv","tag-curso","tag-domina","tag-export","tag-import","tag-into","tag-mysql","tag-para","tag-select","tag-uso","tag-variables"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/29071","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=29071"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/29071\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/29072"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=29071"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=29071"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=29071"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}