mysql
  1. mysql-literals-constants

Literals (Constants) in MySQL

Literals or constants are fixed values that do not change during the execution of a program. In MySQL, there are different types of literals that you can use to assign values to variables, parameters, or expressions. In this tutorial, we'll discuss the different types of literals in MySQL.

Syntax

There are different types of literals in MySQL, including:

  • Numeric literals: Integer or floating-point numbers.
  • String literals: Sequences of characters enclosed in single or double quotes.
  • Date and time literals: Date, time, and timestamp values formatted as strings.
  • Boolean literals: TRUE or FALSE.

Here are some examples of each type of literal in MySQL:

-- Numeric literals
SET count = 5;
SET price = 3.14;

-- String literals
SET message = 'Hello, world!';
SET name = "John Doe";

-- Date and time literals
SET date = '2022-01-01';
SET time = '12:34:56';
SET timestamp = '2022-01-01 12:34:56';

-- Boolean literals
SET flag = TRUE;
SET enabled = FALSE;

Example

Let's say we want to assign a value to a variable called "favoriteColor". We can use a string literal to do this:

SET favoriteColor = 'blue';

Now, we can use the "favoriteColor" variable in our MySQL queries:

SELECT * FROM products WHERE color = favoriteColor;

Output

When we run the query above, MySQL will return all products that match the color "blue".

Explanation

In the example above, we used a string literal to assign a value to a variable called "favoriteColor". We then used the variable in a MySQL query to filter products by the "color" column.

Use

Literals or constants are useful for assigning fixed values to variables, parameters, or expressions. They can improve the readability of code and make it easier to understand the intent of the variables or expressions.

Important Points

  • Numeric literals can be decimal, binary, hexadecimal, or octal.
  • String literals can be enclosed in single or double quotes.
  • Date and time literals must be formatted as strings.
  • Boolean literals can be TRUE or FALSE.

Summary

In this tutorial, we discussed the different types of literals in MySQL, including numeric literals, string literals, date and time literals, and boolean literals. We also provided examples and explanations of each type of literal, as well as their use and important points to consider. By understanding these fundamentals, you can use literals effectively in your MySQL queries and improve the readability of your code.

Published on: