Bobcares

MySQL materialized views | Explained

by | Aug 12, 2022

Let’s quickly discuss what MySQL materialized views are, how they work, and how to implement them in MySQL. Bobcares answers all your questions, small or large as part of our MySQL support.

What Are Materialized Views?

Materialized views are the pre-calculated results of a query that is generally stored in a table. These object types are super useful when you need an immediate response in need, whereas a regular MySQL query would take a long time to process. MySQL does not have default values by itself. But you can easily build Materialized Views.

Materialized Views can be refreshed once in a while, it depends on the content and the requirements and how often refresh need. Basically, a Materialized View refresh can be done immediately or deferred to a full or to a certain point in time.

MySQL materialized views

MySQL materialized views Implementation

A short example of how this could be done in the following query:

SELECT COUNT(*)
  FROM MyISAM_table;

it returns immediate results because the counter is stored in the table header.

Let’s take another example to create a table where all InnoDB row counts are stored in

CREATE TABLE innodb_row_count (
    id          INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
  , schema_name VARCHAR(64)  NOT NULL
  , table_name  VARCHAR(64)  NOT NULL
  , row_count   INT UNSIGNED NOT NULL
);

Depending on the required correctness of this information, the table can be refreshed once a day.

One more possibility would be to extract the data from the schema information.

SELECT table_schema, table_name, table_rows
  FROM information_schema.tables
 WHERE table_type = 'BASE TABLE';

Create MySQL materialized views of scheduled events

MySQL events are kind actions that can be scheduled in MySQL. You can schedule the transfer of data between the source and the “materialized view”. The scheduled events can be executed every hour, every day, every week, and months. The MySQL scheduled events are not active by default. However, this can be activated by adding the following syntax:

SET GLOBAL event_scheduler = ON;

another way is to start the MySQL with the flag:

event-scheduler=ENABLED

How to Create MySQL scheduled event syntax

Let’s analyze creating MySQL scheduled event.

First, we define a scheduler to run every day, the better suggestion is to run after business hours so that you can avoid the server down.

For the SQL query dynamically creation you can use GROUP_CONCAT because this has the capacity of fetching a high number of databases.


CREATE EVENT `user_stats_daily` 
  ON SCHEDULE EVERY 1 DAY STARTS '2016-06-29 20:00:00' 
  ON COMPLETION NOT PRESERVE ENABLE 
  COMMENT 'Creates a materialized view with user data' DO BEGIN
      SET GLOBAL group_concat_max_len=1000000;
 select GROUP_CONCAT(CONCAT("SELECT NOW() as last_update,'",samp.name,"' as sampname,
                `name` 'Client name', 
                DATE_FORMAT(IFNULL(`lastLoginDate`,`loginDate`),'%b %d %Y %h:%i %p') 'Last login date', 
                lastLoginIP 'Login IP', 
                active_ 'Active' FROM `DB-", samp.name,
  "_portal`.`organization_`,`DB-",
  samp.name,
  "_portal`.`user_` WHERE `organizationId` in 
                  (select min(organizationId) from `DB-",samp.name,
  "_portal`.`organization_`) 
  ") SEPARATOR ' UNION ALL 
  ') INTO @stmt_sql
  FROM `portal_db`.`samp` samp;


SET @drop_stmt = "drop table if exists DB-APP._b_user_stats;";
PREPARE stmt
FROM @drop_stmt;
 EXECUTE stmt;
SET @sql = concat("create table DB-APP._b_user_stats as ",@stmt_sql);
PREPARE stmt
FROM @sql;
 EXECUTE stmt;
 DEALLOCATE PREPARE stmt;

 END

The ‘samp’ table holds the index of each database. They are numbers from 1 through 200, that is from DB-1 to DB-200 so the SQL will go over all databases.

The tag @stmt_sql is to store the text of the large SQL query as the variable. Once it is created, we can delete the “materialized view” so that just to make sure we start fresh and then create it again using the result of the big SQL query.

Conclusion

To conclude, MySQL materialized views can help to speed up queries, it is super easy to execute if there is a huge amount of data and the databases are not memory-based anymore.

PREVENT YOUR SERVER FROM CRASHING!

Never again
lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server
24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF