SET - (MySQL Misc)
In MySQL, SET is a data type that allows you to store a string of zero or more values. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of SET in MySQL.
Syntax
The syntax for creating a column with the SET data type is as follows:
column_name SET('value1','value2',...,'valueN') NOT NULL
In the above syntax, "column_name" is the name of the column, and the set of values within the parentheses are the possible values that can be stored in the column. The "NOT NULL" constraint ensures that a value is always present.
Example
Let's use the SET data type to create a table called "user" that contains a column called "language" that stores the languages spoken by each user.
CREATE TABLE user (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
language SET('English', 'Spanish', 'French', 'German') NOT NULL
);
We can now insert some data into the "user" table:
INSERT INTO user (name, language) VALUES ('John', 'English,French');
INSERT INTO user (name, language) VALUES ('Maria', 'Spanish');
Output
When we run the example code above, the output will be:
Query OK, 0 rows affected (0.02 sec)
Query OK, 0 rows affected (0.01 sec)
Explanation
In the example above, we created a table called "user" with a column called "language" that uses the SET data type. The possible values for this column are "English", "Spanish", "French", and "German". We then added two rows to the "user" table, specifying the languages spoken by each user.
Use
The SET data type is useful when you have a limited number of possible values that can be assigned to a column. By using SET, you ensure that only valid values are stored in the column, and you can easily query the data based on the individual values within the set.
Important Points
- You can store multiple values in a SET column by separating them with commas.
- You can set a default value for a SET column by using the DEFAULT keyword followed by the desired value(s) within single quotes.
- SET columns can contain up to 64 unique values.
Summary
In this tutorial, we discussed how to use SET data type in MySQL. We covered the syntax, example, output, explanation, use, and important points of SET in MySQL. SET is useful when you have a limited number of possible values that can be assigned to a column. With this knowledge, you can now use SET in MySQL to store strings of zero or more values.