Storing Binary Data: The BLOB Type, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 4.5 Free with a free account

Storing Binary Data: The BLOB Type

Database Programming · Chapter 4: SQL Data Types in DepthSection 4.5 · lesson 24 of 769 min · free with a free account

← Date and Time Data Types: DATE, TIME, and TIMESTAMPNext lesson: Writing Advanced SQL Queries: Techniques and Patterns →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

How BINARY, VARBINARY, and BLOB types store raw bytes like images.

  • Distinguish binary types from character types and read hexadecimal binary literals
  • Compare BINARY, VARBINARY, and BLOB size limits in MySQL, SQL Server, and SQLite
  • Explain the trade-offs between storing files in the database and in external object storage
  • Identify packet limits and query habits that affect large binary values

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,072 words). Read along, or search it.

Opening Question

A PNG Signature Is Eight Bytes

Maya Rao, Lantern Books' owner, needs product images. Should the database hold their bytes? A file contains bytes, not a string of database characters. This query uses only the signature fragment from a P N G image. Run the query, which displays hexadecimal for inspection instead of printing raw binary into a text terminal. The length reports eight bytes. Those bytes identify a familiar file signature, but they do not make a complete picture. Binary large object, or blob, holds raw content such as images, documents, audio, or encrypted payloads. Representation is one decision. Placement is another: must these bytes live inside the database?

Definition

Bytes, Hexadecimal, and Binary Literals

A byte can hold two hundred fifty-six possible values. Hexadecimal writes each byte with two digits, from zero zero through F F. A binary literal begins with X, followed by paired hexadecimal digits in single quotes. Those pairs represent bytes. Run this comparison between a binary value and its printable hexadecimal spelling. The binary value uses two bytes; its hexadecimal spelling has four characters. Printable representations add overhead. The last comparison is false. Uppercase A and lowercase a have different bytes, regardless of text collation. Text types associate stored bytes with a character encoding and collation. Binary types preserve bytes without interpreting them as letters.

Short Binary Types

Fixed BINARY Versus Variable VARBINARY

For short binary values, binary is fixed length, while varbinary allows varying lengths up to its declared limit. The length argument counts bytes. In MySQL, binary eight pads a two-byte input with six zero bytes. Varbinary eight preserves the actual two-byte value, plus length bookkeeping. A S H A two fifty-six digest fits binary thirty-two: thirty-two bytes, versus sixty-four hexadecimal characters. MySQL binary allows at most two hundred fifty-five bytes. Varbinary shares the overall row limit, rather than reserving that entire capacity. SQL Server's ordinary binary and varbinary declarations allow up to eight thousand bytes. Its conversion padding details depend on the source type. Check conversion rules for your engine. Binary preserves byte identity; character types support human language.

Large Binary Types

BLOB Sizes and VARBINARY(MAX)

For larger values, MySQL offers four blob sizes. Tiny blob holds at most two hundred fifty-five bytes; plain blob holds sixty-five thousand, five hundred thirty-five. Medium blob reaches just under sixteen mebibytes, and long blob just under four gibibytes. These are type capacities, not guaranteed upload sizes. Their length prefixes use one through four bytes. Budget payload bytes, rather than text characters. SQL Server uses varbinary max for large ordinary binary values, with a limit just under two gibibytes. Its older image type is deprecated. SQLite has a blob storage class, with its own configured length limits. It does not implement MySQL's four-size family through those type names. Size alone does not choose the type. Text represents characters; blob represents uninterpreted bytes.

Worked Example

Storing Metadata Beside the Payload

Keep descriptive facts in ordinary columns beside the payload. This disposable documents table stores a name, media type, recorded size, and content. The inserted content is a signature fragment. Real uploads usually supply complete file bytes through a bound parameter. Run the insert and metadata query. We compare recorded size with the actual binary length for this small verification. Both report eight. In MySQL, length also counts bytes; SQL Server uses data length for the corresponding byte count. Validate content, size, and allowed format. A media-type label alone does not prove what the file contains. Select needed metadata for listings. Select star fetches the payload too, even when the interface only needs names.

Loading Files

LOAD_FILE and OPENROWSET Bulk Loading

MySQL's load file function reads from the database server's filesystem, not from the computer running the browser or client. It requires the file privilege, a readable file, acceptable size, and compatibility with the server's secure file privilege setting. If a required condition fails, the function returns null. That is a missing value, not an empty binary file. Applications usually read the upload and bind its bytes, avoiding dependence on an arbitrary server-local path. SQL Server has a different bulk route, open row set with single blob. Its binary literal form uses a zero X prefix instead of this X-quoted form. These dialect references are non-run listings. Applications retrieve binary values through their libraries, then write or serve the bytes.

Design Decision

Database Storage Versus External Object Storage

Small signatures can fit inside the database. Transactions keep changes to the row and bytes together. Database content follows its backup and permission arrangements. Growing payloads make backups, restores, and replication heavier. A product-photo catalog may work better with external object storage, while the row holds a file path or object key and metadata. The file service delivers downloads directly. Coordinate changes, missing files, permissions, and backups across both stores. SQL Server's filestream offers a managed middle path. It keeps bytes in the filesystem while integrating them with database transactions and backups. Internal placement also depends on engine and row format. Blob content is not universally stored apart from its row.

Practical Limits

Packet Size and Transfer Limits

A column's theoretical capacity is only one limit. The client and server must also transfer the value within their configured packet limits. MySQL eight's server default for max allowed packet is sixty-four mebibytes. A hundred-mebibyte upload exceeds that setting even with a long blob column. Raise appropriate transfer limits, or consider external storage. Increasing type capacity alone does not solve a packet problem. Large reads consume bandwidth, memory, and cache space. Avoid fetching files just to list their names. Indexing rules depend on the engine. MySQL blob indexes require a prefix length; searching descriptive metadata is usually more useful than comparing complete image bytes. Maya needs a design that fits access and consistency requirements. The largest type is not automatically best.

Quick Check

Counting Bytes in a Hex Literal

A new scanner sends the binary value shown here, including zero bytes before and after its nonzero byte. How many bytes does SQLite's length function report for this blob? Pause and predict. Four bytes, the third choice. Each hexadecimal pair contributes one byte, including each zero pair. Run the query, and the length is four. Eight counts the hexadecimal characters used to write the value, rather than the bytes represented. Zero bytes do not terminate a blob the way they can affect some text operations. Its binary length still includes them.

Key Takeaways

Raw Bytes, Metadata, and Delivery Costs

Choose binary types for raw byte identity, and text types when the value represents characters. Hex is a readable representation of binary data. Keep metadata separate from the payload, select only what is needed, and check practical transfer limits as well as the column type. For Maya's images, weigh transactional consistency against storage and delivery costs. A reliable file design includes coordinated permissions, backups, and retrieval behavior.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Storing Binary Data: The BLOB Type

What is a BLOB in SQL?
A BLOB, or binary large object, is a column type that stores raw bytes such as images, PDFs, audio, or encrypted data without treating them as characters. Text types attach a character encoding and collation to their bytes, while binary types keep each byte exactly as stored. Binary values are often written in hexadecimal, as in X'89504E47', where each pair of hex digits represents one byte, so that literal is four bytes long.
What are the size limits of the MySQL BLOB types?
MySQL has four BLOB types: TINYBLOB holds up to 255 bytes, BLOB up to 65,535 bytes, MEDIUMBLOB just under 16 MiB, and LONGBLOB just under 4 GiB. These are column capacities, not guaranteed upload sizes, because the max_allowed_packet setting, 64 MiB by default in MySQL 8, also limits each transfer. SQL Server uses VARBINARY(MAX), up to just under 2 GiB, rather than a family of BLOB types.
Should you store images in a database or in file storage?
Either can work, and the choice depends on size, consistency, and delivery needs. Keeping bytes in the database places them inside transactions, backups, and permissions, which suits small files. Large, growing collections such as product photos often fit external object storage better, with the table holding a path or object key plus metadata. That design requires coordinating permissions, backups, and missing files across both stores. SQL Server's FILESTREAM offers a middle path.
What is the difference between BINARY and VARBINARY?
BINARY(n) is a fixed-length binary type, while VARBINARY(n) stores variable-length binary values up to n bytes. In MySQL, inserting two bytes into BINARY(8) pads the value with six zero bytes, while VARBINARY(8) keeps the two actual bytes plus a small length prefix. BINARY suits fixed-size values such as a 32-byte SHA-256 digest. MySQL BINARY allows at most 255 bytes, and SQL Server allows n up to 8,000 for both types, with VARBINARY(MAX) for larger values.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →