MySQL Cookbook by

Get full access to MySQL Cookbook and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Using SQL Variables in Queries

You want to save a value from a query so you can refer to it in a subsequent query.

Use a SQL variable to store the value for later use.

As of MySQL 3.23.6, you can assign a value returned by a SELECT statement to a variable, then refer to the variable later in your mysql session. This provides a way to save a result returned from one query, then refer to it later in other queries. The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you’re retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

A common situation in which SQL variables come in handy is when you need to issue successive queries on multiple tables that are related by a common key value. Suppose you have a customers table with a cust_id column that identifies each customer, and an orders table that also has a cust_id column to indicate which customer each order is associated with. If you have a customer name and you want to delete the customer record as well as all the customer’s orders, you need to determine the proper cust_id value for that customer, then delete records from both the customers and orders tables that match the ID. One way to do this is to first save the ID value in a variable, then refer to the variable in the DELETE statements: [ 5 ]

The preceding SELECT statement assigns a column value to a variable, but variables also can be assigned values from arbitrary expressions. The following statement determines the highest sum of the arms and legs columns in the limbs table and assigns it to the @max_limbs variable:

Another use for a variable is to save the result from LAST_INSERT_ID( ) after creating a new record in a table that has an AUTO_INCREMENT column:

LAST_INSERT_ID( ) returns the value of the new AUTO_INCREMENT value. By saving it in a variable, you can refer to the value several times in subsequent statements, even if you issue other statements that create their own AUTO_INCREMENT values and thus change the value returned by LAST_INSERT_ID( ) . This is discussed further in Chapter 11 .

SQL variables hold single values. If you assign a value to a variable using a statement that returns multiple rows, the value from the last row is used:

If the statement returns no rows, no assignment takes place and the variable retains its previous value. If the variable has not been used previously, that value is NULL :

To set a variable explicitly to a particular value, use a SET statement. SET syntax uses = rather than := to assign the value:

A given variable’s value persists until you assign it another value or until the end of your mysql session, whichever comes first.

Variable names are case sensitive:

SQL variables can be used only where expressions are allowed, not where constants or literal identifiers must be provided. Although it’s tempting to attempt to use variables for such things as table names, it doesn’t work. For example, you might try to generate a temporary table name using a variable as follows, but the result is only an error message:

SQL variables are a MySQL-specific extension, so they will not work with other database engines.

[ 5 ] In MySQL 4, you can use multiple-table DELETE statements to accomplish tasks like this with a single query. See Chapter 12 for examples.

Get MySQL Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

mysql variable assignment select

14.4.4 Assignment Operators

Table 14.6 Assignment Operators

Assignment operator. Causes the user variable on the left hand side of the operator to take on the value to its right. The value on the right hand side may be a literal value, another variable storing a value, or any legal expression that yields a scalar value, including the result of a query (provided that this value is a scalar value). You can perform multiple assignments in the same SET statement. You can perform multiple assignments in the same statement.

Unlike = , the := operator is never interpreted as a comparison operator. This means you can use := in any valid SQL statement (not just in SET statements) to assign a value to a variable.

You can make value assignments using := in other statements besides SELECT , such as UPDATE , as shown here:

While it is also possible both to set and to read the value of the same variable in a single SQL statement using the := operator, this is not recommended. Section 11.4, “User-Defined Variables” , explains why you should avoid doing this.

This operator is used to perform value assignments in two cases, described in the next two paragraphs.

Within a SET statement, = is treated as an assignment operator that causes the user variable on the left hand side of the operator to take on the value to its right. (In other words, when used in a SET statement, = is treated identically to := .) The value on the right hand side may be a literal value, another variable storing a value, or any legal expression that yields a scalar value, including the result of a query (provided that this value is a scalar value). You can perform multiple assignments in the same SET statement.

In the SET clause of an UPDATE statement, = also acts as an assignment operator; in this case, however, it causes the column named on the left hand side of the operator to assume the value given to the right, provided any WHERE conditions that are part of the UPDATE are met. You can make multiple assignments in the same SET clause of an UPDATE statement.

In any other context, = is treated as a comparison operator .

For more information, see Section 15.7.6.1, “SET Syntax for Variable Assignment” , Section 15.2.17, “UPDATE Statement” , and Section 15.2.15, “Subqueries” .

Home » MySQL Stored Procedures » MySQL Stored Procedure Variables

MySQL Stored Procedure Variables

Summary : in this tutorial, you will learn about MySQL stored procedure’s variables including how to declare and use them.

A variable is a named data object whose value can change during the execution of a stored procedure .

Typically, you use variables to hold immediate results. These variables are local to the stored procedure.

Before using a variable, you need to declare it.

Declaring variables

To declare a variable inside a stored procedure, you use the DECLARE  statement as follows:

In this syntax:

  • First, specify the name of the variable after the DECLARE keyword. Ensure the variable name adheres to MySQL table column naming rules.
  • Second, define the data type and length of the variable. Variables can have any MySQL data type , such as INT , VARCHAR , and  DATETIME .
  • Third, assign a default value to the variable using the DEFAULT option. If you declare a variable without specifying a default value, its default value is NULL .

The following example declares a variable named totalSale with the data type DEC(10,2) and default value of 0.0 :

MySQL allows you to declare two or more variables that share the same data type using a single DECLARE statement.

For example, the following example declares two integer variables totalQty and  stockCount , and sets their default values to zero.

After declaring a variable, you can start using it.

As of MySQL 8.0.34, it is not possible to declare multiple variables with different data types using a single DECLARE statement.

For example, the following declaration will cause a syntax error:

To fix the error, you need to use multiple DECLARE statements as follows:

Assigning variables

To assign a variable a value, you use the SET statement:

For example:

The value of the total variable is 10  after the assignment.

In addition to the SET  statement, you can use the  SELECT INTO statement to assign the result of a query to a variable as shown in the following example:

In this example:

  • First, declare a variable named productCount and initialize its value to 0 .
  • Then, use the SELECT INTO statement to assign the productCount variable the number of products selected from the products table.

Variable scopes

A variable has its own scope, which determines its lifetime. If you declare a variable inside a stored procedure, it will be out of scope when the END statement of the stored procedure is reached.

When you declare a variable inside the BEGIN...END block, it goes out of scope once the END is reached.

MySQL allows you to declare two or more variables that share the same name in different scopes because a variable is only effective within its scope.

However, declaring variables with the same name in different scopes is not considered good programming practice.

A variable whose name begins with the @ sign is a session variable , available and accessible until the session ends.

MySQL Stored Procedure Variable Example

The following example illustrates how to declare and use a variable in a stored procedure:

How it works.

First, declare a variable totalOrder with a default value of zero. This variable will store the number of orders from the orders table.

Second, use the SELECT INTO   statement to assign the variable totalOrder the number of orders selected from the orders table:

Third, select the value of the variable totalOrder .

Note that you will learn how to use variables practically in the subsequent tutorials. The example in this tutorial serves as an illustration to help you understand the concept.

This statement calls the stored procedure GetTotalOrder() :

Here is the output:

mysql variable assignment select

  • Use variables to hold immediate results in a stored procedure.
  • The scope of a variable determines the variable’s lifetime.

How to Declare and Use Variables in MySQL

  • MySQL Howtos
  • How to Declare and Use Variables in …

User-Defined Variables in MySQL

Initialize user-defined variables, use variables as fields in a select statement, declare local variables in mysql, declare system variables in mysql.

How to Declare and Use Variables in MySQL

In this tutorial article, we will explain how to declare variables within the SQL code for MySQL databases.

On SQL scripts, you can use variables to store values during the execution of a sequence of commands and use them instead of literals.

MySQL recognizes different types of variables. The first type is the user-defined variables, identified by an @ symbol used as a prefix. In MySQL, you can access user-defined variables without declaring or initializing them previously. If you do so, a NULL value is assigned to the variable when initialized. For example, if you use SELECT with a variable without giving a value to it, as in this case:

MySQL returns a NULL value.

To initialize a user-defined variable, you need to use a SET or SELECT statement. You can initialize many variables at once, separating each assignment statement with a comma, like this:

Once you assign a value to a variable, it will have a type according to the given value. In the previous examples, @FirstVar and @SecondVar are of type int .

The lifespan of a user-defined variable lasts as long as the session is active, and it is invisible to other sessions. Once the session closes, the variable disappears.

There are 5 data types you can assign to a user-defined variable:

  • string (binary or nonbinary)
  • floating-point
  • NULL , which can be associated with any type.

To assign a value to a variable, you can use either symbol = or := . The two following statements have the same effect:

Variables can be part of the field lists of a SELECT statement. You can mix variables and field names when you specify fields in a select, as in this example:

Local variables don’t need the @ prefix in their names, but they must be declared before they can be used. To declare a local variable, you can use the DECLARE statement or use it as a parameter within a STORED PROCEDURE declaration.

When you declare a local variable, optionally, a default value can be assigned to it. If you don’t assign any default value, the variable is initialized with a NULL value.

Each variable lives within a scope, delimited by the BEGIN ... END block that contains its declaration.

The following example illustrates two different ways to use local variables: as a procedure parameter and as a variable internal to the procedure:

In the previous example, the variable itemcount is used as a parameter to pass a value to the procedure. That variable is later used in the SELECT statement to multiply the ListPrice field obtained from the table. The local variable factor is used to store a decimal value used to multiply the resulting price.

There is a third type of variable called system variables used to store values that affect individual client connections ( SESSION variables) or affect the entire server operation ( GLOBAL variables).

System variables are usually set at server startup. To do so, you can use the command line or include the SET statement in an option file. But their values can be modified within an SQL script.

System variables can be identified using a double @ sign as a prefix or using the words GLOBAL or SESSION in the SET statement. Another way to differentiate GLOBAL and SESSION system variables is to use a second prefix: global or session . Here are a few examples of how you can assign values to system variables:

To see the system variables in use within a session or in the server, you can use the SHOW VARIABLES statement. You can add a comparison operator to filter this list if you want to get the value of some specific variables. For example:

How to Assign a Value to a Variable in MySQL

  • Small Business
  • Managing Employees
  • Other Managing Employees
  • ')" data-event="social share" data-info="Pinterest" aria-label="Share on Pinterest">
  • ')" data-event="social share" data-info="Reddit" aria-label="Share on Reddit">
  • ')" data-event="social share" data-info="Flipboard" aria-label="Share on Flipboard">

How to Reindex SQL Tables

What is a shareholder proxy, how to create a break even analysis.

  • How to Configure Proxy PAC Files
  • How to Find, Cut and Paste a Cell Range in Microsoft Excel Visual Basic

MySQL user-defined variables are used to pass values from one statement to another. They are connection specific. Values cannot be created by one client and used by another client. The variables are also unset when the connection is closed. Variables are written as "@var_name" where "var_name" can be replaced by any alphanumeric character or the "-", "_" and "$" symbols. They can be assigned using the "=" or ":=" characters. The value can be any datatype supported by the MySQL database.

Log in to the MySQL database.

Assign values to the variables using a "SET" statement

SET @fruit1='apple', @fruit2='orange', @fruit3='pear';

Use either "=" or ":=" to assign variables in a SET statement. String values must be enclosed in single quotes. Numerical values are not enclosed in single quotes.

Assign a value to a variable in a "SELECT" statement:

SELECT @fruit1, @fruit2, @fruit3, @fruit4:='mango';

You must use ":=" if you are assigning a value to a variable in any other type of statement other than the SET statement.

Log out of the MySQL database.

  • MySQL 5.6 Reference Manual: User-Defined Variables

Kristen Waters has been writing for the computer industry since 2004. She has written training materials for both large and small computer companies as well as how-to and informative articles for many online publications. She holds Bachelor of Science degrees from both York College of Pennsylvania and the University of Maryland.

Related Articles

How to add database records using java in netbeans, how to embed a web browser in wpf, how to specify yesterday in sql, how to give your facebook page its own url, getting a count of the elements in a listbox in javascript, how to pass values between pages in wordpress, how to estimate the y intercept in excel, how to change an execute sql task in ssis, how to build a query string in t-sql, most popular.

  • 1 How to Add Database Records Using Java in NetBeans
  • 2 How to Embed a Web Browser in WPF
  • 3 How to Specify Yesterday in SQL
  • 4 How to Give Your Facebook Page Its Own URL

MySQL SELECT INTO Variable

Select Into Variable Statement

In this tutorial, we will learn about the SELECT INTO Variable statement. We will start with the basic introduction to the SELECT INTO Variable statement and then proceed to check its syntax along with some examples. So, let’s get started!

Introduction to MySQL SELECT INTO Variable

The SELECT INTO variable statement is used to save the column value or the query result into another variable. Moreover, you can save the result fetched by the query into a file as well.

To keep the answer short and simple, the SELECT INTO statement will first fetch the data from the table and insert it into the variable or a file.

Let’s now see the syntax of the SELECT INTO variable statement.

MySQL SELECT INTO Variable Syntax

MySQL provides us with the different syntax forms of the SELECT INTO variable statement. We will see them one by one.

Select the data into the variable –

For example-

Note that, we are inserting the value into a single variable. Therefore, the query must fetch a single value. In order to prevent the query from fetching multiple rows, you can use the LIMIT clause or the WHERE clause.

Here, the variables that are defined with the prefix @ are the session variables and they work as long as the current session is active. Once you close the terminal or end the session, those variables won’t work anymore.

Write the data into the file –

Here, the path that you are setting for the outfile must match with the secure-file path that you can find in the my.ini file in the MySQL SERVER folder.

Also, there is no need to set the limit as the file can consist of any number of records that are fetched from the query.

Enough details, let’s see some examples now.

MySQL SELECT INTO Variable Examples

To demonstrate the SELECT INTO variable examples, we will use the following table.

Emps Table Description 1

Selecting the Value into a Single Variable

Now, we will write a query to select the city value of employee ‘mark’ into the new variable and display that value using the new variable.

Select Into Single Variable Example

As you can see, we have received the expected output.

Selecting the Value into a Multiple Variable

If there are multiple values in a single row, we can assign them by creating multiple session variables. See below-

Here, we are fetching the name and the city of the employee having id 1 into the variables ‘name’ and ‘city’.

Let’s display them and see the result.

Select Into Multiple Variable Example

Writing the Data into the File

Using the SELECT INTO variable statement, we can write the data fetched from the query into the file.

Here, the export path of files in my system is given as follows. It might be different in your case. You can check it inside the my.ini file under the ‘secure-file’ option.

Let’s check if the file is created and data is written into it.

Writing Data Into The File

As you can see, the query has been executed successfully, which means the file consisting of the data has been created. Let’s see the file now.

Data Into The File

Here you can see, that all the records have been pasted into the file in a good format.

In this tutorial, we have learned about the SELECT INTO variable statement which is used to store the query result into the variable or a file. We have seen two different syntax as well as their examples. I hope you have learned something valuable and you might try it to enhance your MySQL knowledge.

MySQL Official documentation on the SELECT…INTO statement.

Digital Owl's Prose

Sql and php developer diaries., mysql select into syntax part 1 – uses with variables..

This blog post, will cover examples of MySQL SELECT INTO syntax for storing column values in variables.

various-pink-letters-strewn-about

Photo by  Jason Leung  on  Unsplash

Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any party or organization. OS and DB used:

  • Xubuntu Linux 16.04.5 LTS (Xenial Xerus)
  • MySQL 5.7.23

A Brief Opener

This blog post is part 1 in a series of posts exploring MySQL SELECT INTO syntax. I plan to publish these on Monday’s for a personal blogging theme: ‘MySQL Monday Mini’s’. Hope you enjoy them!

I have this table and trivial data:

To start, I will define a couple of session variables to use for the post. One of data type INTEGER assigned a value of 0, while the other will be set as an empty string to handle a VARCHAR data type:

With SELECT INTO , you are free to place the INTO clause in a couple different areas within the SELECT query.

Here, I place it just after listing the target column of the SELECT clause:

I’ll verify variable @var_id ‘s value with an additional SELECT :

The other option for INTO clause placement, is at the end of the query:

Results are all good with that usage as well.

Can you place the INTO clause just after the target table name of the FROM clause? I am not 100% sure. But we are going to find out. Together. Let’s try and see:

Nope. Lesson learned here.

Multiple variables can be the target of a SELECT INTO clause.

Let’s retrieve the query results for those variables now:

Assignment at the end of the query is also valid:

What if you do not have the same number of SELECT clause columns and variables?

SELECT INTO has great use in Stored Procedures. The demo procedure here will return a string to the caller containing the name associated with the correct id , which is supplied as an argument. Up first, the procedure’s definition:

Then, CALL the procedure, supplying id 15 as the parameter:

Like what you have read? See anything incorrect? Please share your thoughts and comments below. Thanks for reading!!!

Explore the official MySQL 5.7 Online Manual for more information.

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.

Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, are performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

Share this:

3 thoughts on “ mysql select into syntax part 1 – uses with variables. ”.

  • Pingback: The STRICT keyword with SELECT INTO – examples in PostgreSQL | Digital Owl's Prose
  • Pingback: MySQL SELECT INTO Syntax Part 3 – DUMPFILE with examples. | Digital Owl's Prose
  • Pingback: MySQL SELECT INTO Syntax Part 2 – Saving to OUTFILE with examples | Digital Owl's Prose

Hey thanks for commenting! Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Discover more from Digital Owl's Prose

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

On this website we use first or third-party tools that store small files (<i>cookie</i>) on your device. Cookies are normally used to allow the site to run properly (<i>technical cookies</i>), to generate navigation usage reports (<i>statistics cookies</i>) and to suitable advertise our services/products (<i>profiling cookies</i>). We can directly use technical cookies, but <u>you have the right to choose whether or not to enable statistical and profiling cookies</u>. <b>Enabling these cookies, you help us to offer you a better experience</b>.

MySQL Tutorial

  • MySQL Basics
  • MySQL - Home
  • MySQL - Introduction
  • MySQL - Features
  • MySQL - Versions
  • MySQL - Variables
  • MySQL - Installation
  • MySQL - Administration
  • MySQL - PHP Syntax
  • MySQL - Node.js Syntax
  • MySQL - Java Syntax
  • MySQL - Python Syntax
  • MySQL - Connection
  • MySQL - Workbench
  • MySQL Databases
  • MySQL - Create Database
  • MySQL - Drop Database
  • MySQL - Select Database
  • MySQL - Show Database
  • MySQL - Copy Database
  • MySQL - Database Export
  • MySQL - Database Import
  • MySQL - Database Info
  • MySQL Users
  • MySQL - Create Users
  • MySQL - Drop Users
  • MySQL - Show Users
  • MySQL - Change Password
  • MySQL - Grant Privileges
  • MySQL - Show Privileges
  • MySQL - Revoke Privileges
  • MySQL - Lock User Account
  • MySQL - Unlock User Account
  • MySQL Tables
  • MySQL - Create Tables
  • MySQL - Show Tables
  • MySQL - Alter Tables
  • MySQL - Rename Tables
  • MySQL - Clone Tables
  • MySQL - Truncate Tables
  • MySQL - Temporary Tables
  • MySQL - Repair Tables
  • MySQL - Describe Tables
  • MySQL - Add/Delete Columns
  • MySQL - Show Columns
  • MySQL - Rename Columns
  • MySQL - Table Locking
  • MySQL - Drop Tables
  • MySQL - Derived Tables
  • MySQL Queries
  • MySQL - Queries
  • MySQL - Constraints
  • MySQL - Insert Query
  • MySQL - Select Query
  • MySQL - Update Query
  • MySQL - Delete Query
  • MySQL - Replace Query
  • MySQL - Insert Ignore
  • MySQL - Insert on Duplicate Key Update
  • MySQL - Insert Into Select
  • MySQL Views
  • MySQL - Create Views
  • MySQL - Update Views
  • MySQL - Drop Views
  • MySQL - Rename Views
  • MySQL Indexes
  • MySQL - Indexes
  • MySQL - Create Index
  • MySQL - Drop Index
  • MySQL - Show Indexes
  • MySQL - Unique Index
  • MySQL - Clustered Index
  • MySQL - Non-Clustered Index
  • MySQL Operators and Clauses
  • MySQL - Where Clause
  • MySQL - Limit Clause
  • MySQL - Distinct Clause
  • MySQL - Order By Clause
  • MySQL - Group By Clause
  • MySQL - Having Clause
  • MySQL - AND Operator
  • MySQL - OR Operator
  • MySQL - Like Operator
  • MySQL - IN Operator
  • MySQL - ANY Operator
  • MySQL - EXISTS Operator
  • MySQL - NOT Operator
  • MySQL - NOT EQUAL Operator
  • MySQL - IS NULL Operator
  • MySQL - IS NOT NULL Operator
  • MySQL - Between Operator
  • MySQL - UNION Operator
  • MySQL - UNION vs UNION ALL
  • MySQL - MINUS Operator
  • MySQL - INTERSECT Operator
  • MySQL - INTERVAL Operator
  • MySQL Joins
  • MySQL - Using Joins
  • MySQL - Inner Join
  • MySQL - Left Join
  • MySQL - Right Join
  • MySQL - Cross Join
  • MySQL - Full Join
  • MySQL - Self Join
  • MySQL - Delete Join
  • MySQL - Update Join
  • MySQL - Union vs Join
  • MySQL - Unique Key
  • MySQL - Primary Key
  • MySQL - Foreign Key
  • MySQL - Composite Key
  • MySQL - Alternate Key
  • MySQL Triggers
  • MySQL - Triggers
  • MySQL - Create Trigger
  • MySQL - Show Trigger
  • MySQL - Drop Trigger
  • MySQL - Before Insert Trigger
  • MySQL - After Insert Trigger
  • MySQL - Before Update Trigger
  • MySQL - After Update Trigger
  • MySQL - Before Delete Trigger
  • MySQL - After Delete Trigger
  • MySQL Data Types
  • MySQL - Data Types
  • MySQL - VARCHAR
  • MySQL - BOOLEAN
  • MySQL - ENUM
  • MySQL - DECIMAL
  • MySQL - INT
  • MySQL - FLOAT
  • MySQL - BIT
  • MySQL - TINYINT
  • MySQL - BLOB
  • MySQL - SET
  • MySQL Regular Expressions
  • MySQL - Regular Expressions
  • MySQL - RLIKE Operator
  • MySQL - NOT LIKE Operator
  • MySQL - NOT REGEXP Operator
  • MySQL - regexp_instr() Function
  • MySQL - regexp_like() Function
  • MySQL - regexp_replace() Function
  • MySQL - regexp_substr() Function
  • MySQL Fulltext Search
  • MySQL - Fulltext Search
  • MySQL - Natural Language Fulltext Search
  • MySQL - Boolean Fulltext Search
  • MySQL - Query Expansion Fulltext Search
  • MySQL - ngram Fulltext Parser
  • MySQL Functions & Operators
  • MySQL - Date and Time Functions
  • MySQL - Arithmetic Operators
  • MySQL - Numeric Functions
  • MySQL - String Functions
  • MySQL - Aggregate Functions
  • MySQL Misc Concepts
  • MySQL - NULL Values
  • MySQL - Transactions
  • MySQL - Using Sequences
  • MySQL - Handling Duplicates
  • MySQL - SQL Injection
  • MySQL - SubQuery
  • MySQL - Comments
  • MySQL - Check Constraints
  • MySQL - Storage Engines
  • MySQL - Export Table into CSV File
  • MySQL - Import CSV File into Database
  • MySQL - UUID
  • MySQL - Common Table Expressions
  • MySQL - On Delete Cascade
  • MySQL - Upsert
  • MySQL - Horizontal Partitioning
  • MySQL - Vertical Partitioning
  • MySQL - Cursor
  • MySQL - Stored Functions
  • MySQL - Signal
  • MySQL - Resignal
  • MySQL - Character Set
  • MySQL - Collation
  • MySQL - Wildcards
  • MySQL - Alias
  • MySQL - ROLLUP
  • MySQL - Today Date
  • MySQL - Literals
  • MySQL - Stored Procedure
  • MySQL - Explain
  • MySQL - JSON
  • MySQL - Standard Deviation
  • MySQL - Find Duplicate Records
  • MySQL - Delete Duplicate Records
  • MySQL - Select Random Records
  • MySQL - Show Processlist
  • MySQL - Change Column Type
  • MySQL - Reset Auto-Increment
  • MySQL - Coalesce() Function
  • MySQL Useful Resources
  • MySQL - Useful Functions
  • MySQL - Statements Reference
  • MySQL - Quick Guide
  • MySQL - Useful Resources
  • MySQL - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

MySQL - SET Syntax for Variable Assignment

Mysql set statement, setting values to user defined variables, setting values to local variables, setting values to system variables.

The SET statement in MySQL is used to assign values for variables. Using this you can set values to, user-defined variables, variables in procedures and, system variables.

Following is the syntax of the SET statement in MySQL−

You can create variables with in the current MySQL session and use them in the queries. While defining a user d-fined variable you need to place '@' before the variable name.

You can retrieve the values of these variables using the SELECT statement as −

The above query produces the following output −

You can define variables with in stored routines and set values to them using the SET statement.

Following is an example of declaring local variables −

You can call the above procedure as follows −

Following is the output of the above query −

MySQL system variables holds global or session level values, these variables are used to configure various operations. You can set values to these variables dynamically using the SET statement

Let us verify whether loading local data is enabled, if not you can observe the local_infile variable value as −

The above mysql query generates the following output −

Following query enables local_infile option as −

If you verify the value of the variable local_infile again, you can observe the changed value as −

Following is the output of the above mysql query −

MarketSplash

How To Decide Between TSQL Vs MySQL For Your Database Needs

This article compares TSQL and MySQL, focusing on their core differences, performance, and compatibility. Ideal for developers, we'll examine each system's strengths and applications, providing clarity on choosing the right tool for your database needs.

💡 KEY INSIGHTS

  • T-SQL is closely integrated with Microsoft products and offers advanced features for complex stored procedures and functions, which is beneficial for applications deeply integrated with Microsoft services.
  • MySQL , being open-source, adheres more closely to standard SQL syntax, making it suitable for cross-platform compatibility and cost-effective for small to medium-sized projects.
  • Both systems are optimized for quick query processing, but T-SQL provides more comprehensive tools for query optimization and execution plans.
  • Security in both systems is robust, with features like authentication, role-based access control, and SQL injection prevention, but T-SQL might offer more advanced features for enterprise environments.

In the world of database management, T-SQL and MySQL stand as two prominent technologies, each with unique features and applications. This article explores the key differences and similarities between them, offering insights for programmers and developers. We'll examine how each system impacts database operations, helping you make informed decisions in your projects.

mysql variable assignment select

T-SQL Vs. MySQL: Core Differences

Syntax variations in t-sql and mysql, performance comparison: speed and efficiency, security features: t-sql and mysql, frequently asked questions.

T-SQL and MySQL have distinct origins and design philosophies. T-SQL, primarily used with Microsoft SQL Server, is a Microsoft extension to the SQL standard. MySQL, on the other hand, is an open-source relational database management system that uses standard SQL.

Language Syntax

Stored procedures and functions, transaction control, error handling.

The syntax of T-SQL and MySQL differs in various aspects. T-SQL often includes proprietary syntax elements, making it more tightly integrated with Microsoft products. MySQL adheres more closely to the standard SQL syntax, which is beneficial for cross-platform compatibility.

Example : SELECT Statements

T-SQL is known for its robust support for complex stored procedures and functions. MySQL also supports stored procedures but with a different syntax and less complexity.

Example : Creating a Stored Procedure

Both T-SQL and MySQL support transaction control, but with different approaches and levels of sophistication.

Example : Transaction Control

T-SQL provides a comprehensive error handling mechanism with TRY...CATCH blocks, whereas MySQL's error handling is less sophisticated.

Example : Error Handling

Understanding these core differences helps developers choose the right tool for their specific needs and leverage the strengths of each system effectively.

T-SQL and MySQL differ significantly in their syntax, impacting how queries and scripts are written. These variations can affect everything from basic commands to complex operations.

String Concatenation

Date functions, variable assignment, table creation.

In T-SQL, the + operator is used for string concatenation, while MySQL uses the CONCAT() function.

T-SQL Example:

MySQL Example:

Date manipulation functions also vary. T-SQL uses GETDATE() , while MySQL uses NOW() for the current date and time.

Pagination syntax is another area of difference. T-SQL uses the OFFSET-FETCH clause, whereas MySQL uses LIMIT with OFFSET .

The method of assigning values to variables differs too. T-SQL uses SET or SELECT , while MySQL primarily uses SET .

Even creating tables shows syntax differences, especially in specifying default values and auto-increment fields.

Understanding these syntax variations is crucial for database developers working across both T-SQL and MySQL environments, as it enables more efficient and error-free coding.

Comparing T-SQL and MySQL in terms of performance involves considering several factors including query execution speed, efficiency in handling large datasets, and the optimization capabilities of each system.

Query Execution Speed

Optimization capabilities.

Both T-SQL and MySQL are optimized for quick query processing. However, the specific performance can vary based on the complexity of the queries and the underlying hardware.

Example: Simple SELECT Query

T-SQL provides comprehensive tools for query optimization, including detailed execution plans. MySQL also offers optimization tools but they may be less detailed compared to T-SQL.

Example: Execution Plan Retrieval

Security is a paramount concern in database management, and both T-SQL and MySQL offer a range of security features to protect data integrity and prevent unauthorized access.

Authentication And Authorization

Role-based access control, sql injection prevention.

Both systems provide robust authentication mechanisms. T-SQL, as part of SQL Server, integrates with Windows authentication for a seamless security experience. MySQL supports its own authentication system and can be configured for external authentication methods.

Role-based access control (RBAC) is supported in both T-SQL and MySQL. This allows the assignment of permissions to roles, which can then be assigned to users, simplifying the management of user privileges.

Example: Creating a Role and Assigning Permissions

Both T-SQL and MySQL are susceptible to SQL injection attacks if not properly managed. They both support prepared statements and parameterized queries, which are vital for preventing these attacks.

Example: Parameterized Query

Understanding and utilizing the security features of T-SQL and MySQL is crucial for protecting sensitive data and ensuring a secure database environment. Both offer strong security capabilities, but their implementation and management can differ, depending on the system's architecture and the specific requirements of the database application.

Can I use T-SQL with databases other than SQL Server?

T-SQL is specifically designed for Microsoft SQL Server and is not natively compatible with other database management systems. Some T-SQL features might be replicated in other systems, but full compatibility is not guaranteed.

Is MySQL suitable for large, enterprise-level applications?

MySQL can be used for enterprise-level applications, especially when configured and optimized correctly. However, for applications deeply integrated with Microsoft services or requiring advanced SQL Server features, T-SQL might be a better fit.

How do security features compare between T-SQL and MySQL?

Both T-SQL and MySQL offer robust security features including authentication, authorization, encryption, and SQL injection prevention. T-SQL, through SQL Server, might have more advanced features suited for enterprise environments, while MySQL provides sufficient security capabilities for a wide range of applications.

Which is more cost-effective, T-SQL or MySQL?

MySQL is generally more cost-effective for small to medium-sized projects due to its open-source nature. T-SQL, part of Microsoft SQL Server, can incur higher costs, especially for larger implementations, due to licensing fees.

Let’s test your knowledge!

Which database system is known for its robust support for complex stored procedures and functions?

How to choose between mysql text vs varchar for your database.

  • How To Optimize Database Performance With MySQL HeatWave
  • How To Choose Between MySQL Vs Postgres For Your Next Project
  • How To Use MySQL Split String For Efficient Data Manipulation
  • How To Use MySQL ROW_NUMBER For Effective Data Management
  • How To Enhance Your Workflow With MySQL GUI Tools

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

IMAGES

  1. MySQL SELECT INTO Variable

    mysql variable assignment select

  2. MySQL Variables

    mysql variable assignment select

  3. SELECT in MySQL

    mysql variable assignment select

  4. MySQL Tutorials for Business Analyst: MySQL SELECT Statement with Examples

    mysql variable assignment select

  5. MySQL Variables

    mysql variable assignment select

  6. MySQL Tutorial for Beginners 25

    mysql variable assignment select

VIDEO

  1. Database assignment MySQL Workbench query ISMT

  2. MYSQL

  3. MYSQL Select Queries

  4. C++ Variables, Literals, an Assignment Statements [2]

  5. JavaScript variable assignment const variable

  6. How to install MySQL 8.0.36 server and workbench for windows 11/10. Check the installed version

COMMENTS

  1. SET a variable in SELECT statement

    Variable assignment with mysql. 0. MySQL: Assign column value to variable. 32. ... Mysql add variable in select statement. 1. MySQL: variable = variable + select statement. 0. Setting variables in SELECT statement mysql. Hot Network Questions Does the "gradual brain replacement" thought experiment prove consciousness is independent of substrate?

  2. MySQL SELECT INTO Variable

    Introduction to MySQL SELECT INTO variable statement. To store the result set of a query in one or more variables, you use the SELECT INTO variable statement. Here's the syntax of the SELECT INTO variable statement: SELECT c1, c2, c3, ... INTO @v1, @v2, @v3,...

  3. 15.7.6.1 SET Syntax for Variable Assignment

    The following discussion describes the syntax options for setting and persisting system variables: To assign a value to a global system variable, precede the variable name by the GLOBAL keyword or the @@GLOBAL. qualifier: Press CTRL+C to copy. SET GLOBAL max_connections = 1000; SET @@GLOBAL.max_connections = 1000;

  4. MySQL Variables

    To create a user-defined variable, you use the following syntax: In this syntax, @variable_name is a user-defined variable. It is preceded by the @ symbol. In MySQL, user-defined variables are case-insensitive, meaning that @id and @ID are the same variables. Note that user-defined variables are the MySQL-specific extension to SQL standard.

  5. Using SQL Variables in Queries

    As of MySQL 3.23.6, you can assign a value returned by a SELECT statement to a variable, then refer to the variable later in your mysql session. This provides a way to save a result returned from one query, then refer to it later in other queries. The syntax for assigning a value to a SQL variable within a SELECT query is @var_name := value ...

  6. MySQL :: MySQL 8.0 Reference Manual :: 11.4 User-Defined Variables

    One way to set a user-defined variable is by issuing a SET statement: SET @var_name = expr [, @var_name = expr] ... For SET , either = or := can be used as the assignment operator. User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL value.

  7. MySQL Variables

    Assigning value to a single variable . In MySQL, you can initialize variables using the SET or SELECT statements. With the SET statement . The SET statement syntax for the value-assigning task is as follows: SET @var_name := value; The standard syntax of the SET command includes the := operator, but you can use := or = to assign value to the ...

  8. MySQL :: MySQL 8.0 Reference Manual :: 14.4.4 Assignment Operators

    14.4.4 Assignment Operators. Assignment operator. Causes the user variable on the left hand side of the operator to take on the value to its right. The value on the right hand side may be a literal value, another variable storing a value, or any legal expression that yields a scalar value, including the result of a query (provided that this ...

  9. MySQL Stored Procedure Variables

    The value of the total variable is 10 after the assignment. In addition to the SET statement, you can use the SELECT INTO statement to assign the result of a query to a variable as shown in the following example: DECLARE productCount INT DEFAULT 0; SELECT COUNT (*) INTO productCount FROM products; Code language: SQL (Structured Query Language ...

  10. How to Declare and Use Variables in MySQL

    To initialize a user-defined variable, you need to use a SET or SELECT statement. You can initialize many variables at once, separating each assignment statement with a comma, like this: SET @FirstVar=1, @SecondVar=2; Once you assign a value to a variable, it will have a type according to the given value. In the previous examples, @FirstVar and ...

  11. How to Assign a Value to a Variable in MySQL

    Assign a value to a variable in a "SELECT" statement: SELECT @fruit1, @fruit2, @fruit3, @fruit4:='mango'; You must use ":=" if you are assigning a value to a variable in any other type of ...

  12. MySQL SELECT INTO Variable

    Introduction to MySQL SELECT INTO Variable. The SELECT INTO variable statement is used to save the column value or the query result into another variable. Moreover, you can save the result fetched by the query into a file as well. To keep the answer short and simple, the SELECT INTO statement will first fetch the data from the table and insert ...

  13. MySQL SELECT INTO Syntax Part 1

    This blog post, will cover examples of MySQL SELECT INTO syntax for storing column values in variables. Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any […]

  14. mysql

    From my understanding the only difference between user variables @var and local variables like var is the latter are scoped between the BEGIN and END statements of a procedure whereas user variables exist for use in the connection as long as the connection remains open. So I would like to use local variables since I don't care if the variables ...

  15. mysql

    mysql > select 1 into @a; Here @a is user defined variable and 1 is going to be assigned in @a. Now how to get or select the value of @{variable_name}. we can use select statement like. Example :-mysql > select @a; it will show the output and show the value of @a. Now how to assign a value from a table in a variable.

  16. MySQL

    The SET statement in MySQL is used to assign values for variables. Using this you can set values to, user-defined variables, variables in procedures and, system variables. Syntax. Following is the syntax of the SET statement in MySQL−. SET variable = val1, val2, val3, . . .

  17. How To Use MySQL Declare Variable In Your Database Projects

    Once variables are declared in MySQL, setting and modifying them is a common task. Use the SET or SELECT statement to assign values to your variables after declaration. SET variable_name = value; -- Example: SET userAge = 30; 📌. This code sets the previously declared userAge variable to 30.

  18. MySQL: SELECT to local variable in stored procedure

    The problem was my declared local variable id . After I changed her name, everything worked just fine. My previous answer was: I don't know what the problem was, but I did found a solution. I wrote: SELECT MIN(ID) FROM WORKER WHERE CARDNUMBER = cardUID INTO @workerId; SELECT @workerId; instead of. SET @workerId = (SELECT MIN(ID) FROM WORKER ...

  19. sql

    When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value) As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one ...

  20. How To Decide Between TSQL Vs MySQL For Your Database Needs

    Variable Assignment. The method of assigning values to variables differs too. T-SQL uses SET or SELECT, while MySQL primarily uses SET. T-SQL Example:-- T-SQL variable assignment DECLARE @MyVar INT; SET @MyVar = 10; MySQL Example:-- MySQL variable assignment SET @MyVar := 10;

  21. MySql set multiple variables from one select

    Is there a way to set multiple variables in one SELECT query in MySQL? 3. ... MySQL store procedure Assign value to multiple variable from select statement. 0. Select into multiple varibales with MySQL. 0. How to set multiple Out variable value from single Select Query From Store Procedure.