MySQL: Declaring Variables

MySQL declaring variables

In this guide, we will explain declaring variables in MySQL with syntax and examples.

What is a variable in MySQL?

In MySQL, a variable allows a programmer to store data temporarily during the execution of code.

Syntax

The syntax to declare a variable in MySQL is:

DECLARE variable_name datatype [ DEFAULT initial_value ]

Parameters or Arguments

variable_nameThe name to assign to the variable.datatypeThe datatype to assign to the variable.DEFAULT initial_valueOptional. It is the value initially assigned to the variable when it is declared. If an initial_value is not specified, the variable is assigned a value of NULL.

Example – Declaring a variable

Below is an example of how to declare a variable in MySQL called vSite.

DECLARE vSite VARCHAR(40);

This example would declare a variable called vSite as a VARCHAR(40) data type.

You can then later set or change the value of the vSite variable, as follows:

SET vSite = 'adglob.in';

This SET statement would set the vSite variable to a value of ‘adglob.in’.

Example – Declaring a variable with an initial value (not a constant)

Below is an example of how to declare a variable in MySQL and give it an initial value. This is different from a constant in that the variable’s value can be changed later.

DECLARE vSite VARCHAR(40) DEFAULT 'adglob.in';

This would declare a variable called vSite as a VARCHAR(40) data type and assign an initial value of ‘adglob.in’.

You could later change the value of the vSite variable, as follows:

SET vSite = 'CheckYourMath.com';

This SET statement would change the vSite variable from a value of ‘adglob.in’ to a value of ‘CheckYourMath.com’.

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply