」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 用於提升資料庫效能的頂級 ySQL 架構檢查

用於提升資料庫效能的頂級 ySQL 架構檢查

發佈於2024-11-19
瀏覽:344

A database schema defines the logical structure of your database, including tables, columns, relationships, indexes, and constraints that shape how data is organized and accessed. It’s not just about how the data is stored but also how it interacts with queries, transactions, and other operations.

These checks can help you stay on top of any new or lingering problems before they snowball into bigger issues. You can dive deeper into these schema checks below and find out exactly how to fix any issues if your database doesn't pass. Just remember, before you make any schema changes, always backup your data to protect against potential risks that might occur during modifications.

1. Primary Key Check (Missing Primary Keys)

The primary key is a critical part of any table, uniquely identifying each row and enabling efficient queries. Without a primary key, tables may experience performance issues, and certain tools like replication and schema change utilities may not function properly.

There are several issues you can avoid by defining a primary key when designing schemas:

  1. If no primary or unique key is specified, MySQL creates an internal one, which is inaccessible for usage.
  2. The lack of a primary key could slow down replication performance, especially with row-based or mixed replication.
  3. Primary keys allow scalable data archiving and purging. Tools like pt-online-schema-change require a primary or unique key.
  4. Primary keys uniquely identify rows, which is crucial from an application perspective.

Example

To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use the following SQL:

ALTER TABLE Persons ADD PRIMARY KEY (ID);

To define a primary key on multiple columns:

ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID, LastName);

Note: If you use the ALTER TABLE command, then the primary key column(s) must have been declared to not contain NULL values when the table was first created.

2. Table Engine Check(Deprecated Table Engine)

The MyISAM storage engine is deprecated, and tables still using it should be migrated to InnoDB. InnoDB is the default and recommended engine for most use cases due to its superior performance, data recovery capabilities, and transaction support. Migrating from MyISAM to InnoDB can dramatically improve performance in write-heavy applications, provide better fault tolerance, and allow for more advanced MySQL features such as full-text search and foreign keys.

Why InnoDB is preferred:

  • Crash recovery capabilities allow it to recover automatically from database server or host crashes without data corruption.
  • Only locks the rows affected by a query, allowing for much better performance in high-concurrency environments.
  • Caches both data and indexes in memory, which is preferred for read-heavy workloads.
  • Fully ACID-compliant, ensuring data integrity and supporting transactions.
  • The InnoDB engine receives the majority of the focus from the MySQL development community, making it the most up-to-date and well-supported engine.

How to Migrate to InnoDB

ALTER TABLE  ENGINE=InnoDB;

3. Table Collation Check (Mixed Collations)

Using different collations across tables or even within a table can lead to performance problems, particularly during string comparisons and joins. If the collations of two string columns differ, MySQL might need to convert the strings at runtime, which can prevent indexes from being used and slow down your queries.

When you make changes to mixed collations tables, a few problems can surface:

  • Collations can differ at the column level, so mismatches at the table level won’t cause issues if the relevant columns in a join have matching collations.
  • Changing a table's collation, especially with a charset switch, isn't always simple. Data conversion might be needed, and unsupported characters could turn into corrupted data.
  • If you don’t specify a collation or charset when creating a table, it inherits the database defaults. If none are set at the database level, server defaults will apply. To avoid these issues, it’s important to standardize the collation across your entire dataset, especially for columns that are frequently used in join operations.

How to Change Collation Settings

Before making any changes to your database's collation settings, test your approach in a non-production environment to avoid unintended consequences. If you're unsure about anything, it’s best to consult with a DBA.

Retrieve the default charset and collation for all databases:

SELECT SCHEMA_NAME, DEFAULT_CHARACTER_SET_NAME, 
DEFAULT_COLLATION_NAME FROM INFORMATION_SCHEMA.SCHEMATA;

Check the collation of specific tables:

SELECT TABLE_SCHEMA, TABLE_NAME, TABLE_COLLATION FROM
information_schema.TABLES WHERE TABLE_COLLATION IS NOT NULL ORDER BY
TABLE_SCHEMA, TABLE_COLLATION;

Find the server's default charset:

SELECT @@GLOBAL.character_set_server;

Find the server's default collation:

SELECT @@GLOBAL.collation_server;

Update the collation for a specific database:

ALTER DATABASE  COLLATE=;

Update the collation for a specific table:

ALTER TABLE  COLLATE=;

4. Table Character Set Check (Mixed Character Set)

Mixed character sets are similar to mixed collations in that they can lead to performance and compatibility issues. A mixed character set occurs when different columns or tables use different encoding formats for storing data.

  • Mixed character sets can hurt join performance on string columns by preventing index use or requiring value conversions.
  • Character sets can be defined at the column level, and as long as the columns involved in a join have matching character sets, performance won’t be impacted by mismatches at the table level.
  • Changing a table’s character set may involve data conversion, which can lead to corrupted data if unsupported characters are encountered.
  • If no character set or collation is specified, tables inherit the database's defaults, and databases inherit the server's default charset and collation.

How to Change Character Settings

Before adjusting your database's character settings, be sure to test the changes in a staging environment to prevent any unexpected issues. If you're uncertain about any steps, consult a DBA for guidance.

Retrieve the default charset and collation for all databases:

SELECT SCHEMA_NAME,DEFAULT_CHARACTER_SET_NAME,
DEFAULT_COLLATION_NAME FROM INFORMATION_SCHEMA.SCHEMATA;

Get the character set of a column:

SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, CHARACTER_SET_NAME 
FROM information_schema.COLUMNS WHERE CHARACTER_SET_NAME is not NULL 
ORDER BY TABLE_SCHEMA, CHARACTER_SET_NAME;

Find the server's default charset:

SELECT @@GLOBAL.character_set_server;

Find the server's default collation:

SELECT @@GLOBAL.collation_server;

To view the structure of a table:

show create table 
;

Example output:

CREATE TABLE `
` ( `word` varchar(50) NOT NULL DEFAULT '', `sid` int(10) unsigned NOT NULL DEFAULT '0', `langcode` varchar(12) CHARACTER SET ascii NOT NULL DEFAULT '', `type` varchar(64) CHARACTER SET ascii NOT NULL, `score` float DEFAULT NULL, PRIMARY KEY (`word`,`sid`,`langcode`,`type`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

To change a column character set:

ALTER TABLE  MODIFY `type` varchar(64) CHARACTER SET utf8mb4 NOT NULL;

5. Column Auto Increment Check(Type of Auto Increment Columns)

For tables that are expected to grow indefinitely and use auto-increment for primary keys, it's recommended to switch to the UNSIGNED BIGINT data type. This allows the column to handle a much larger range of values, preventing the need for costly table alterations in the future once the maximum value is reached. By specifying UNSIGNED, only positive values are stored, effectively doubling the range of the data type.

How to Change Character Settings

To modify the column type to UNSIGNED BIGINT:

ALTER TABLE .
MODIFY COLUMN id bigint unsigned NOT NULL AUTO_INCREMENT;

6. Table Foreign Key Check(Existence of foreign keys)

Foreign keys offer data consistency by maintaining the relationship between parent and child tables, but they also impact database performance. Each time a write operation occurs, additional lookups are required to verify the integrity of the related data. This can cause slowdowns, especially in high-traffic environments.

If performance is a concern, you may want to consider removing foreign keys, especially in scenarios where data consistency can be handled at the application level.

How to Remove Foreign Keys

To drop a foreign key constraint from a table:

SHOW CREATE TABLE .
; ALTER TABLE .
DROP CONSTRAINT ;

7. Duplicated Index Check

Duplicate indexes in MySQL consume unnecessary disk space and create additional overhead during write operations, as every index must be updated. This can complicate query optimization, potentially leading to inefficient execution plans without offering any real benefit.

Identify and remove duplicate indexes to streamline query optimization and reduce overhead. But make sure that the index is not being used for critical queries before removing it.

8. Unused Index Check

Unused indexes in MySQL can negatively impact database performance by consuming disk space, increasing processing overhead during inserts, updates, and deletes, and slowing down overall operations. While indexes are valuable for speeding up queries, those that aren't used can create unnecessary strain on your system.
Additional benefits of removing unused or duplicate indexes include:

  • With fewer indexes, MySQL's optimizer has fewer choices to evaluate, simplifying query execution and reducing CPU/memory usage.
  • Removing unused indexes frees up valuable disk space that can be used for more critical data, also improving I/O efficiency.
  • Index maintenance tasks, such as rebuilding or reorganizing, become faster and less resource-intensive when the number of indexes is minimized. This leads to smoother operations, particularly in environments requiring 24/7 uptime.

To identify unused indexed in MySQL or MariabDB please use to following SQL statement:

SELECT CONCAT(object_schema, '.', object_name) AS 'table', index_name
FROM performance_schema.table_io_waits_summary_by_index_usage
WHERE index_name IS NOT NULL
AND count_star = 0
AND index_name  'PRIMARY'
AND object_schema NOT IN ('mysql', 'performance_schema', 'information_schema')
ORDER BY count_star, object_schema, object_name;

How to Remove Unused or Duplicated Indexes

In MySQL 8.0 and later, you can make indexes invisible to test whether they’re needed without fully dropping them:

ALTER TABLE  ALTER INDEX  INVISIBLE;

If performance remains unaffected, the index can be safely dropped:

ALTER TABLE  DROP INDEX ;

You can revert an index back to visible if needed:

ALTER TABLE  ALTER INDEX  VISIBLE;

Schema Checks Now Available with Releem

With the latest update, Releem now includes comprehensive schema health checks. These checks provide real-time insights into your database’s structural integrity, along with actionable recommendations for fixing any detected issues.

Top ySQL Schema Checks to Boost Database Performance

By automating the schema monitoring process, Releem takes the guesswork out of manual checks, saving database engineers tons of time and effort. Instead of spending hours working on schema details, you can now focus on more pressing tasks.

版本聲明 本文轉載於:https://dev.to/drupaladmin/top-8-mysql-schema-checks-to-boost-database-performance-3m4k?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • PHP 中的 Elvis 運算子是什麼以及它如何運作?
    PHP 中的 Elvis 運算子是什麼以及它如何運作?
    馴服PHP 中的Elvis 運算子(?:)神秘的?: 運算子為某些PHP 程式碼增色不少,讓您感到困惑。這篇簡明的文章深入探討了其神秘的本質,並揭示了其真正的目的。 揭開 ?: 運算子?: 運算符,也稱為「Elvis 運算符, " 功能類似三元運算符。然而,它的獨特之處在於沒有一個表達式...
    程式設計 發佈於2024-11-19
  • 如何在Java中以毫秒精度提取當前時間?
    如何在Java中以毫秒精度提取當前時間?
    在Java中以毫秒精度提取當前時間以YYYY-MM-DD HH:MI:Sec格式獲取當前時間.毫秒,需要對所提供的程式碼進行擴充。修改的關鍵在於細化SimpleDateFormat模式。 提供的程式碼檢索目前時間,不含毫秒資訊:public static String getCurrentTimeS...
    程式設計 發佈於2024-11-19
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-11-19
  • 如何從 MongoDB 陣列中刪除物件?
    如何從 MongoDB 陣列中刪除物件?
    MongoDB:從陣列中移除物件在MongoDB 中,您可以使用$ 從嵌入在文件中的陣列中刪除物件拉操作員。如果您希望從陣列中刪除特定對象,則需要提供與確切對象匹配的查詢。 考慮以下文件:{ _id: 5150a1199fac0e6910000002, name: 'some name'...
    程式設計 發佈於2024-11-19
  • 儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    解決PHP 中的POST 請求故障在提供的程式碼片段:action=''而非:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"檢查$_POST陣列:表單提交後使用 var_dump 檢查 $_POST 陣列的內容...
    程式設計 發佈於2024-11-19
  • 前端控制器設計模式在 PHP 應用程式中的作用是什麼?
    前端控制器設計模式在 PHP 應用程式中的作用是什麼?
    理解前端控制器設計模式作為一個踏入PHP世界的新手,您可能遇到過“前端控制器”這個術語。 「這種模式對於組織和維護應用程式的結構至關重要。讓我們深入研究一下它的功能和實現。什麼是前端控制器?前端控制器是處理所有傳入請求的中央集線器。的更改,而不會影響應用程式的其餘部分。所有請求重定向到指定的入口點,...
    程式設計 發佈於2024-11-19
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-11-19
  • 如何使用 mysqldb 將 MySQL 表轉換為 Python 中的字典清單?
    如何使用 mysqldb 將 MySQL 表轉換為 Python 中的字典清單?
    Python: 使用mysqldb 將MySQL 表轉換為字典物件清單將MySQL 表轉換為字典物件清單Python,您可以利用mysqldb庫提供的DictCursor 類別。透過利用這個遊標類,您可以方便地將表中的每一行轉換為對應的字典。 若要使用DictCursor,請依照下列步驟操作:連接到...
    程式設計 發佈於2024-11-19
  • 為什麼使用者必須雙擊才能使用網站上的顯示隱藏按鈕?
    為什麼使用者必須雙擊才能使用網站上的顯示隱藏按鈕?
    雙擊困境:顯示-隱藏按鈕滯後的簡單修復在您的網站上實現顯示-隱藏按鈕時,您可能會遇到意想不到的問題:使用者必須第一次雙擊按鈕才能切換隱藏元素。這種行為可能會令人沮喪,因此讓我們深入研究一個簡單的解決方案以確保點擊功能。 在提供的 JavaScript 程式碼中,showhidemenu() 函數負責...
    程式設計 發佈於2024-11-19
  • 如何使用遞歸宏迭代宏參數?
    如何使用遞歸宏迭代宏參數?
    宏參數上的 Foreach 宏在程式設計領域,宏提供了執行重複任務的便捷方法。然而,嘗試建立一個迭代另一個巨集的參數的巨集可能會帶來挑戰。讓我們探討如何克服這個障礙並深入研究遞歸宏的領域。 遞歸巨集可用來遍歷傳遞給巨集的參數清單。然而,這種方法可能容易出錯,因為它可能會導致無限遞歸。為了解決這個問題...
    程式設計 發佈於2024-11-19
  • 學習編碼?避免過度使用人工智慧工具
    學習編碼?避免過度使用人工智慧工具
    如果您剛開始編碼,使用 AI 產生代碼聽起來可能是成功的捷徑。但實際上,它可能會以你可能沒有意識到的方式阻礙你。事情是這樣的:作為一名新程式設計師,您的主要重點應該是學習基礎知識並打下堅實的基礎。編碼不是魔法,也不是寫優美的詩。它是向電腦提供清晰的逐步指令來完成真正的事情。 以 JavaScrip...
    程式設計 發佈於2024-11-19
  • 如何在 C++ 中對所有可變參數模板參數呼叫函數?
    如何在 C++ 中對所有可變參數模板參數呼叫函數?
    C 可變參數模板:在所有模板參數上調用函數在C 中,通常需要迭代可變參數模板參數並執行特定操作,例如調用一個函數。這可以使用以下任一方法來實現:C 17 Fold Expression(f(args), ...);但是,如果被呼叫的函數可能傳回一個物件對於重載的逗號運算符,您應該使用:((void)...
    程式設計 發佈於2024-11-19
  • 使用 html css 和 javascript 的導覽列抽屜 https://www.instagram.com/webstreet_code/
    使用 html css 和 javascript 的導覽列抽屜 https://www.instagram.com/webstreet_code/
    在 Instagram 上關注我們:https://www.instagram.com/webstreet_code/ 抽屜 *{ 保證金:0; 填充:0; 框大小:邊框框; 字體系...
    程式設計 發佈於2024-11-19
  • 如何存取 Python `pytz` 庫中所有可用時區的清單?
    如何存取 Python `pytz` 庫中所有可用時區的清單?
    如何列出 Pytz 時區Python 的 pytz 函式庫提供了大量時區來處理時態資料。如果您希望探索時區參數的所有可能值,請按照下列步驟操作:使用pytz.all_timezones要取得所有可用時區的完整列表,請使用pytz 的all_timezones 屬性:import pytz pytz....
    程式設計 發佈於2024-11-19
  • 如何在 JavaScript 中解析和格式化 ISO 8601 日期字串?
    如何在 JavaScript 中解析和格式化 ISO 8601 日期字串?
    在JavaScript 中解析ISO 8601 日期字串在JavaScript 中處理日期時,您可能會遇到ISO 8601 日期字串,它遵循特定的規則格式:CCYY-MM-DDThh:mm:ssTZD。為了存取和操作這些日期,讓我們探索一個簡單而有效的解決方案。 值得慶幸的是,JavaScript ...
    程式設計 發佈於2024-11-19

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3