CodeWithSQL.com
Search Engine Optimization (SEO)

Creating SEO-Friendly URLs with the 'to_slug' MySQL Function

Mohammad 2021-01-06

In the digital era, having user-friendly URLs is crucial for enhancing website visibility and search engine optimization (SEO). However, managing URLs that include special characters, spaces, or non-ASCII characters can be challenging. In this blog post, we will introduce you to a handy SQL function called "to_slug" that can help you convert any string into a clean and SEO-friendly URL format. Whether you're a web developer, content manager, or SEO enthusiast, this function will streamline the process of creating attractive and accessible URLs.


CREATE FUNCTION to_slug(
    input_string NVARCHAR(4000),
    max_length INT,
    separator_char CHAR(1)
)
RETURNS NVARCHAR(4000)
DETERMINISTIC
BEGIN
    -- Step 1: Transliterate non-ASCII characters to ASCII
    SET input_string = REPLACE(input_string, N'á', 'a');
    SET input_string = REPLACE(input_string, N'é', 'e');
    SET input_string = REPLACE(input_string, N'í', 'i');
    SET input_string = REPLACE(input_string, N'ó', 'o');
    SET input_string = REPLACE(input_string, N'ú', 'u');
    SET input_string = REPLACE(input_string, N'ñ', 'n');
    SET input_string = REPLACE(input_string, N'ç', 'c');
    SET input_string = REPLACE(input_string, N'À', 'A');
    SET input_string = REPLACE(input_string, N'È', 'E');
    SET input_string = REPLACE(input_string, N'Ì', 'I');
    SET input_string = REPLACE(input_string, N'Ò', 'O');
    SET input_string = REPLACE(input_string, N'Ù', 'U');

    -- Step 2: Remove non-alphanumeric characters and duplicate spaces
    SET input_string = LOWER(
        REGEXP_REPLACE(
            REGEXP_REPLACE(input_string, ' ', separator_char),
            '[^a-z0-9-]', ''
        )
    );

    -- Step 3: Trim the slug to the maximum length
    SET input_string = LEFT(input_string, max_length);

    -- Step 4: Remove any trailing separator characters
    WHILE RIGHT(input_string, 1) = separator_char DO
        SET input_string = LEFT(input_string, CHAR_LENGTH(input_string) - 1);
    END WHILE;

    -- Step 5: Handle empty or blank slugs
    IF CHAR_LENGTH(input_string) = 0 THEN
        SET input_string = 'str_0';
    END IF;

    RETURN input_string;
END;

Understanding the "to_slug" Function

The "to_slug" function is a powerful SQL utility designed to convert a given string into a URL-friendly slug format. It is an invaluable tool for web developers and content creators who need to generate clean, readable URLs from various text-based inputs.

Let's break down the steps of the "to_slug" function:

  1. Step 1: Transliterate non-ASCII characters to ASCII
  2. The function starts by transliterating non-ASCII characters into their ASCII equivalents. This ensures that international characters, such as accented letters, are converted to their simpler, English-friendly counterparts. For example, "á" becomes "a," "é" becomes "e," and so on.

  3. Step 2: Remove non-alphanumeric characters and duplicate spaces
  4. Next, the function removes any non-alphanumeric characters and replaces duplicate spaces with the specified separator character. This step ensures that the resulting slug contains only letters, numbers, and the chosen separator, making it SEO-friendly and easy to read.

  5. Step 3: Trim the slug to the maximum length
  6. Sometimes, you may need to limit the length of your URLs for better aesthetics or technical reasons. The "to_slug" function allows you to specify the maximum length of the slug, and it will automatically trim the URL accordingly.

  7. Step 4: Remove any trailing separator characters
  8. In some cases, the string conversion may result in trailing separator characters at the end of the slug. The function takes care of this by removing any unwanted separator characters at the end.

  9. Step 5: Handle empty or blank slugs
  10. The function considers cases where the input string contains no valid characters after processing. In such situations, it generates a default slug to avoid any potential issues.

Example Usage

Let's see the "to_slug" function in action with a simple example. Suppose we have a product table with the following data:

Product ID Product Name Description
1 Super Cool Product This is a very cool product.
2 Awesome Product You will love this awesome product!
3 Amazing Item This item will amaze you with its features.

Now, let's use the "to_slug" function to generate SEO-friendly slugs for the product names:


        SELECT
            ProductID,
            ProductName,
            to_slug(ProductName, 50, '-') AS Slug,
            Description
        FROM
            Products;
        

The output will be:

Product ID Product Name Slug Description
1 Super Cool Product super-cool-product This is a very cool product.
2 Awesome Product awesome-product You will love this awesome product!
3 Amazing Item amazing-item This item will amaze you with its features.

Benefits and Use Cases

Implementing the "to_slug" function in your web development projects or content management systems can yield several advantages:

  1. Improved SEO: Search engines prefer URLs with descriptive slugs, which can positively impact your website's search rankings.
  2. Enhanced User Experience: User-friendly URLs make it easier for visitors to understand the content of a page by glancing at its URL.
  3. Clean Data Representation: The "to_slug" function helps you maintain consistent and readable URLs, even when handling user-generated content.

Conclusion

Incorporating the "to_slug" function into your SQL toolbox can significantly simplify the process of generating clean and SEO-friendly URLs. By converting any input string into a slug format, you can ensure that your website's URLs are both search engine optimized and user-friendly. Whether you're working on a personal blog, an e-commerce platform, or a content-rich website, the "to_slug" function is a valuable addition to your development arsenal.

Streamline your URL generation process today with the "to_slug" function and experience the benefits of cleaner, more accessible URLs for your web projects!

Back to Blog