0
0
MysqlConceptBeginner · 3 min read

What is BLOB in MySQL: Definition and Usage

In MySQL, a BLOB (Binary Large Object) is a data type used to store large amounts of binary data such as images, audio, or files. It allows you to save raw bytes directly in the database instead of text.
⚙️

How It Works

A BLOB in MySQL works like a special container that holds binary data, which means data that is not readable text but raw bytes. Imagine it as a digital box where you can store pictures, videos, or any file exactly as they are, without changing them into characters.

Unlike normal text fields that store letters and numbers you can read, a BLOB keeps the data in its original form. This is useful because files like images or audio need to be stored exactly as they are to be used later.

MySQL offers different sizes of BLOB types (like TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB) depending on how much data you want to store, similar to choosing different sized boxes for different amounts of stuff.

💻

Example

This example shows how to create a table with a BLOB column and insert a small binary file into it.

sql
CREATE TABLE files (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100),
  data BLOB
);

INSERT INTO files (name, data) VALUES ('example_image', LOAD_FILE('/path/to/image.jpg'));

SELECT id, name, LENGTH(data) AS size FROM files;
Output
id | name | size ---|---------------|------ 1 | example_image | 20480
🎯

When to Use

Use BLOB columns when you need to store binary data directly in your MySQL database. This is common for applications that manage files like images, videos, PDFs, or any non-text data.

For example, a photo-sharing app might store user-uploaded pictures in a BLOB column. Another use case is storing encrypted data or backups as binary blobs.

However, if files are very large or accessed frequently, sometimes storing them outside the database (like in a file system or cloud storage) and saving only the file path in the database is better for performance.

Key Points

  • BLOB stores binary data exactly as it is.
  • There are different sizes: TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB.
  • Useful for images, audio, files, and encrypted data.
  • Large files might be better stored outside the database.

Key Takeaways

A BLOB in MySQL stores raw binary data like images or files.
Choose the BLOB size type based on the data size you need to store.
Use BLOBs when you want to keep binary data inside the database.
For very large files, consider storing them outside the database for better performance.