都内で働くSEの技術的なひとりごと / Technical soliloquy of System Engineer working in Tokyo

都内でサラリーマンやってます。SQL Server を中心とした (2023年からは Azure も。) マイクロソフト系(たまに、OSS系などマイクロソフト以外の技術も...)の技術的なことについて書いています。日々の仕事の中で、気になったことを技術要素関係なく気まぐれに選んでいるので記事内容は開発言語、インフラ等ばらばらです。なお、当ブログで発信、発言は私個人のものであり、所属する組織、企業、団体等とは何のかかわりもございません。ブログの内容もきちんと検証して使用してください。英語の勉強のため、英語の

UPDATE STATISTICS の MAXDOP を指定してみる

 今週も怒涛の一週間が過ぎました。12月は毎年出張が多く(忘年会込)、来週は大阪→新潟→徳島の順で出張します。前回、統計更新でどのような処理が走るのか簡単に書いてみました。
ryuchan.hatenablog.com

 記事の中で下記のようなクエリを実行しました。

USE AdventureWorks;  
GO  
UPDATE STATISTICS Production.WorkOrder PK_WorkOrder_WorkOrderID WITH FULLSCAN;  
GO

 UPDATE STATISTICS は OPTION(MAXDOP.. で最大並列数がコントロールができません。サーバの設定が下記の場合、UPDATE STATISTICS を実行すると、裏での処理は MAXDOP 16 で実行されていまいます。
f:id:koogucc11:20161203194504p:plain

SELECT StatMan([SC0]) FROM (SELECT TOP 100 PERCENT [WorkOrderID] AS [SC0] FROM [Production].[WorkOrder] WITH (READUNCOMMITTED)  ORDER BY [SC0] ) AS _MS_UPDSTATS_TBL  OPTION (MAXDOP 16)

 しかし、ちょっとした工夫で MAXDOP をコントロールすることが可能です。新たにデータベースを作成し、下記の通り設定します。
f:id:koogucc11:20161203194737p:plain

 下記のクエリを SQL Server Management Studio で実行します。

USE Sample;  
GO  
UPDATE STATISTICS AdventureWorks.Production.WorkOrder PK_WorkOrder_WorkOrderID WITH FULLSCAN;  
GO

 SQL Server Profiler で参照すると、データベースで指定した MAXDOP の値が有効になります。統計情報更新時に負荷コントロールをするのに有効な方法かと思います。

SELECT StatMan([SC0]) FROM (SELECT TOP 100 PERCENT [WorkOrderID] AS [SC0] FROM [Production].[WorkOrder] WITH (READUNCOMMITTED)  ORDER BY [SC0] ) AS _MS_UPDSTATS_TBL  OPTION (MAXDOP 1)

るるぶ大阪'17 (国内シリーズ)

るるぶ大阪'17 (国内シリーズ)

るるぶ新潟 佐渡'17 (国内シリーズ)

るるぶ新潟 佐渡'17 (国内シリーズ)

るるぶ徳島 鳴門 祖谷渓 (国内シリーズ)

るるぶ徳島 鳴門 祖谷渓 (国内シリーズ)

統計情報更新の動作を SQL Server Profiler を使って観察してみる

 統計情報の更新についての動作を SQL Server Profiler を使って観察してみましょう。今回は下記の条件下で観察します。
f:id:koogucc11:20161127134704p:plain

f:id:koogucc11:20161127191214p:plain

f:id:koogucc11:20161116051019p:plain

 データベースは、AdventureWorks、テーブルは Production.WorkOrder 統計は PK_WorkOrder_WorkOrderID を使用します。まず下記のクエリを SQL Server Management Studio で実行し、統計情報を更新しましょう。

USE AdventureWorks;  
GO  
UPDATE STATISTICS Production.WorkOrder PK_WorkOrder_WorkOrderID WITH FULLSCAN;  
GO

f:id:koogucc11:20161127135414p:plain

 統計情報更新を促すため、下記のクエリを SQL Server Management Studio で実行しましょう。(多めに更新してます。)

USE AdventureWorks
INSERT INTO
    Production.WorkOrder(ProductID, OrderQty, ScrappedQty, StartDate, EndDate, DueDate, ScrapReasonID, ModifiedDate)
    SELECT
        TOP 50000 ProductID,
        OrderQty,
        ScrappedQty,
        StartDate,
        EndDate,
        DueDate,
        ScrapReasonID,
        ModifiedDate
    FROM
        Production.WorkOrder

f:id:koogucc11:20161127141153p:plain

 SQL Server Profiler を起動して、トレースを取得します。
f:id:koogucc11:20161127141509p:plain

 下記のクエリを SQL Server Management Studio で実行します。

SELECT
    ProductID,
    OrderQty,
    ScrappedQty,
    StartDate,
    EndDate,
    DueDate,
    ScrapReasonID,
    ModifiedDate
FROM
    Production.WorkOrder
WHERE
    WorkOrderID BETWEEN 95000 AND 100000

f:id:koogucc11:20161127190038p:plain

 ここで SQL Server Profiler を参照してみましょう。何やら赤枠部分に出力されていますね。
f:id:koogucc11:20161127190249p:plain

SELECT
    StatMan([SC0])
FROM
    (
        SELECT
            TOP 100 PERCENT [WorkOrderID] AS [SC0]
        FROM
            [Production].[WorkOrder] WITH(READUNCOMMITTED)
        ORDER BY
            [SC0]
    ) AS _MS_UPDSTATS_TBL OPTION(MAXDOP 2)

 統計情報を生成するために実テーブルにアクセスしているクエリです。プログラムが発行するクエリの直前に発行されます。
f:id:koogucc11:20161127194258p:plain

 MAXDOP はサーバ設定値に従います。サーバの MAXDOP を 0 のままにしておくと、MAXDOP 16 でクエリが発行されます。(なぜ 16 なのかは不明です。ハードコーディングだったりww) しかし、これだとテーブルの件数が多いものは自動更新は使用できませんね。統計情報更新の考え方としては下記記事の内容で問題ないんですね。
ryuchan.hatenablog.com

 統計情報の更新はシステム規模に合わせてきちんと設計する必要がありますね。

 高すぎー。128,000 円!!

f:id:koogucc11:20161127193505p:plain

便利な SQL の関数とか、構文とか、その他色々まとめてみる - その15 ( GROUPING して、ROLLUP で総計出してみる ) -

 本日は一年ぶりの金沢に出張です。新幹線が 2017年3月に開業してから、金沢駅周辺も賑わってますね。
www.pref.ishikawa.jp

 今日は石川県立音楽堂にて、ある学会に参加してます。
ongakudo.jp

 さて、今回はデータの合計を得るためのクエリを書いてみます。下記のクエリを SQL Server Management Studio で実行してみましょう。

SELECT 
    [製品名] = CASE WHEN (GROUPING(p.Name) = 1) THEN 
                   N'総合計'
               ELSE 
                   ISNULL(p.Name, 0)
               END,
    [オーダー数量] = SUM(OrderQty)
FROM 
    Sales.SalesOrderDetail sod
    INNER JOIN Production.Product p ON
    p.ProductID = sod.ProductID
GROUP BY 
    p.Name WITH ROLLUP
ORDER BY 
    p.Name

f:id:koogucc11:20161126151627p:plain

 通常このような結果を得るには、ある程度複雑なクエリを記述する必要がありますが、GROUPING と ROLLUP を使用すると簡単に記述することができます。

 結構、出張で訪れている金沢ですが、観光したことはほとんどありません。

るるぶ金沢 能登 加賀温泉郷'17 ちいサイズ (国内シリーズ小型)

るるぶ金沢 能登 加賀温泉郷'17 ちいサイズ (国内シリーズ小型)

SQL Server 2016 SP1 がリリースされたので、ちょっとみてみる

 週後半はアレルギー症状が出てしまい、まったくダメダメな状態。ハウスダストアレルギーと寒暖差アレルギー持ちとしては、いつ発症するかわからないので年中辛いです。日曜日に体調が復活したので、朝から近くのドトールで記事書きます。
f:id:koogucc11:20161120100704j:plain

 11月16日に SQL Server 2016 SP1 がリリースされたので、インストールして中身確認してみます。
blogs.msdn.microsoft.com

In addition to a consistent programmability experience across all editions, SQL Server 2016 SP1 also introduces all the supportability and diagnostics improvements first introduced in SQL 2014 SP2, as well as new improvements and fixes centered around performance, supportability, programmability and diagnostics based on the learnings and feedback from customers and SQL community.

 SQL Server 2014 SP2 で追加した機能も SQL Server 2016 SP1 に追加されています。SQL Server 2014 SP2 の機能に関しては下記のブログを参照してください。
ryuchan.hatenablog.com
ryuchan.hatenablog.com
ryuchan.hatenablog.com
ryuchan.hatenablog.com

 Standard Ed. = EnterPrise Ed. となった感じですね。Standard Ed. に対して凄まじい機能追加ですね!但し、パーティショニング、オンラインインデックス操作などは引き続き EnterPrise Ed. のみの機能になっています。大規模かつシステム停止が難しいシステムは Enterprise を選択する必要があります。
f:id:koogucc11:20161118163752p:plain

Database Cloning – Clone database is a new DBCC command added that allows DBAs and support teams to troubleshoot existing production databases by cloning the schema and metadata, statistics without the data. Cloned databases is not meant to be used in production environments. To see if a database has been generated from a call to clonedatabase you can use the following command, select DATABASEPROPERTYEX(‘clonedb’, ‘isClone’). The return value of 1 is true, and 0 is false. In SQL Server 2016 SP1, DBCC CLONEDATABASE added supports cloning of CLR, Filestream/Filetable, Hekaton and Query Store objects. DBCC CLONEDATABASE in SQL 2016 SP1 gives you the ability to generate query store only, statistics only, or pure schema only clone without statistics or query store. A CLONED database always contains the schema and the default clone also contains the statistics and query store data. For more information refer KB 3177838.

 ついに CLONEDATABASE が 2016 にも搭載されました。かつ、2014 SP2 の機能から拡張されています。
ryuchan.hatenablog.com

 下記のオプションが 2016 SP1 で拡張されているようです。

–– SCHEMA AND QUERY STORE ONLY CLONE
DBCC CLONEDATABASE  (source_database_name, target_database_name) WITH NO_STATISTICS
–– SCHEMA AND STATISTICS ONLY CLONE
DBCC CLONEDATABASE  (source_database_name, target_database_name) WITH NO_QUERYSTORE
–– SCHEMA ONLY CLONE
DBCC CLONEDATABASE  (source_database_name, target_database_name) WITH NO_STATISTICS,NO_QUERYSTORE

CREATE OR ALTER (Yes, we heard you !!!) – New CREATE OR ALTER support makes it easier to modify and deploy objects like Stored Procedures, Triggers, User–Defined Functions, and Views. This was one of the highly requested features by developers and SQL Community.

 DROP IF もいい感じでしたが、これもいい感じですね。これもセットアップスクリプトなど簡易化できそうです。.NET で ConcurrentDictionary の AddOrUpdate メソッドが出た時のことを思い出しました。IF 文での判定が減るのは良いことですね。
ryuchan.hatenablog.com

New USE HINT query option – A new query option, OPTION(USE HINT(‘

 クエリヒントが追加されています。開発者視点ていうと HINT 句 だけでいいのは敷居が下がった感じでいいですね。これはあとで試してみよう。

Programmatically identify LPIM to SQL service account – New sql_memory_model, sql_memory_model_desc columns in DMV sys.dm_os_sys_info to allow DBAs to programmatically identify if Lock Pages in Memory (LPIM) privilege is in effect at the service startup time.

Programatically identify IFI privilege to SQL service account – New column instant_file_initialization_enabled in DMV sys.dm_server_services to allow DBAs to programmatically identify if Instant File initialization (IFI) is in effect at the SQL Server service startup.

 これも地味にいい機能!dmv で確認できるのは、環境チェックを省力化できますね。
f:id:koogucc11:20161120064616p:plain

Tempdb supportability – A new Errorlog message indicating the number of tempdb files and notifying different size/autogrowth of tempdb data files at server startup.

 これは SQL Server 2014 SP2 と同様ですかね。

Extended diagnostics in showplan XML – Showplan XML extended to support Memory grant warning, expose max memory enabled for the query, information about enabled trace flags, memory fractions for optimized nested loop joins, query CPU time, query elapsed time, top waits, and information about parameters data type.

 確かに。これもチューニングにおいて非常に役立ちます。これもあとで試してみよう。
f:id:koogucc11:20161120065709p:plain

Lightweight per–operator query execution profiling – Dramatically reduces performance overhead of collecting per–operator query execution statistics such as actual number of rows. This feature can be enabled either using global startup TF 7412, or is automatically turned on when an XE session containing query_thread_profile is enabled. When the lightweight profiling is on, the information in sys.dm_exec_query_profiles is also available, enabling the Live Query Statistics feature in SSMS and populating a new DMF sys.dm_exec_query_statistics_xml.

 軽量なプロファイリングですか。これもあとで試してみよう。

New DMF sys.dm_exec_query_statistics_xml – Use this DMF to obtain actual query execution showplan XML (with actual number of rows) for a query which is still being executed in a given session (session id as input parameter). The showplan with a snapshot of current execution statistics is returned when profiling infrastructure (legacy or lightweight) is on.

 セッションID を引数にして、sql_handle、plan_handle、query_lan を取得できます。

New DMF for incremental statistics – New DMF sys.dm_db_incremental_stats_properties to expose information per–partition for incremental stats.

Better correlation between diagnostics XE and DMVs – Query_hash and query_plan_hash are used for identifying a query uniquely. DMV defines them as varbinary(8), while XEvent defines them as UINT64. Since SQL server does not have “unsigned bigint”, casting does not always work. This improvement introduces new XEvent action/filter columns equivalent to query_hash and query_plan_hash except they are defined as INT64 which can help correlating queries between XE and DMVs.

 SQL Server 2014 SP2 と同じですかね。

Better troubleshooting for query plans with push–down predicate – New EstimatedlRowsRead attribute added in showplan XML for better troubleshooting and diagnostics for query plans with push down predicates.

 EstimatedlRowsRead プロパティの追加ですね。チューニングの時に役立ちますね。

Removing noisy Hekaton logging messages from Errorlog – With SQL 2016, Hekaton engine started logging additional messages in SQL Errorlog for supportability and troubleshooting which was overwhelming and flooded the Errorlog with hekaton messages. Based on feedback from DBAs and SQL community, starting SQL 2016 SP1, the Hekaton logging messages are reduced to minimal in Error log as shown below.

 きちんと見たことないかも...

Improved AlwaysOn Latency Diagnostics – New XEvents and Perfmon diagnostics capability added to troubleshoot latency more efficiently.

Manual Change Tracking Cleanup – New cleanup stored procedure sp_flush_CT_internal_table_on_demand introduced to clean the change tracking internal table on demand. For more information, refer KB 3173157.

DROP TABLE support for replication – DROP TABLE DDL support for replication to allow replication articles to be dropped. For more information, refer KB 3170123.

 SQL Server 2014 SP2 と同じですかね。

Signed Filestream RsFx Driver on Windows Server 2016/Windows 10– The Filestream RsFx driver introduced with SQL Server 2016 SP1 is signed and certified using Windows Hardware Developer Center Dashboard portal (Dev Portal) allowing SQL Server 2016 SP1 Filestream RsFx driver to be installed on Windows Server 2016/Windows 10 without any issue. For more information on this issue, refer to the SQL Tiger team blog post here.

 上記の通りですね。

Bulk insert into heaps with auto TABLOCK under TF 715 – Trace Flag 715 enables table lock for bulk load operations into heap with no non–clustered indexes. When this trace flag is enabled, bulk load operations acquires bulk update (BU) locks when bulk copying data into a table. Bulk update (BU) locks allow multiple threads to bulk load data concurrently into the same table while preventing other processes that are not bulk loading data from accessing the table. The behavior is similar to when the user explicitly specifies TABLOCK hint while performing bulk load or when the sp_tableoption table lock on bulk load is on for a given table however enabling this TF makes this behavior by default without making any query changes or database changes. For more information, refer to the SQL Tiger team blog post here.

 ここに詳しく書いてあります。非クラスタ化インデックスのバルクインサートで 60% くらい削減できたようです。
blogs.msdn.microsoft.com

Parallel INSERT..SELECT Changes for Local temp tables – With SQL Server 2016, Parallel INSERT in INSERT…SELECT operations was introduced. INSERTs into user tables required TABLOCK hint for parallel inserts while INSERTs into local temporary tables were automatically enabled for parallelism without having to designate the TABLOCK hint that user tables require. In a batch workload, INSERT parallelism significantly improves query performance but if there’s a significant concurrent workload trying to run parallel inserts, it causes considerable contention against PFS pages which reduces the overall throughput of the system. This behavior introduced regression in OLTP workload migrating to SQL Server 2016. With SQL Server 2016 SP1, Parallel INSERTs in INSERT..SELECT to local temporary tables is disabled by default and will require TABLOCK hint for parallel insert to be enabled.

 INSERT SELECTのパラレルINSERTはデフォルトで無効になっているので、パラレル INSERT を有効にするには TABLOCK ヒントが必要になります。

The full versions of the WideWorldImporters sample databases now work with Standard Edition and Express Edition, starting SQL Server 2016 SP1. No changes were needed in the sample. The database backups created at RTM for Enterprise edition simply work with Standard and Express in SP1. Download is here: https://github.com/Microsoft/sql-server-samples/releases/tag/wide-world-importers-v1.0

 SP1 に合わせて WideWorldImporters がアップデートされています。GitHub に公開されています。
github.com

 来週から詳しく見ていかないと....

そろそろ、冬支度。前シーズンにゴーグル壊れたし、新調しよ。

OAKLEY(オークリー) スノーゴーグル メンズ OO7074-02

OAKLEY(オークリー) スノーゴーグル メンズ OO7074-02

知らなかったことを記事にしてみる

 眠い。徹夜での仕事になりそうなので、頭をリフレッシュさせるために記事書きます。昨日面白いこと知ったので、実験してみます。私のマシンの CPU コア数は 4コアです。
f:id:koogucc11:20161116051019p:plain

 下記のクエリを SQL Server Management Studio で実行します。スケジューラーは 4つ存在しますね。

SELECT * FROM sys.dm_os_schedulers

f:id:koogucc11:20161116051130p:plain

 ここで実験。下図のように設定し、SQL Server を再起動します。
f:id:koogucc11:20161116051259p:plain

 もう一度クエリを実行します。スケジューラーが指定した通り、48つ存在します。
f:id:koogucc11:20161116051635p:plain

¥ 99,800 で売ってる。倍くらいになってる....

 

シアトルでの思ったことを書いてみた

 先ほど帰国し、成田エクスプレスで自宅へ向かっています。シアトル滞在で思ったことを綴ります。移動を合わせて計8日間の旅(夏休みより長いww)でした。初のサミット参加は非常に刺激的で色々考えさせられるいい機会になりました。
ryuchan.hatenablog.com
ryuchan.hatenablog.com
ryuchan.hatenablog.com

 まず、行く前から分かっていたことですが、『英語力のなさ』。サミットに参加する上での致命傷でした。セッションのすべてを理解できないのはもちろんのこと、最高の技術者を目の前にして、質問の一つもできない、ましてや意見・フィードバックするのは夢のまた夢、といった状況でした。対照的に諸外国の参加者は非常に積極的に質問・意見・フィードバックを矢継ぎ早に行っていました。英語力は必須ですね。付け加えて、自分の意見を積極的に発信する力も同様です。

 あともう一つ。相手を賞賛すること。マイクロソフトのレドモンドキャンパスまでのシャトルバスの中での出来事です。おそらく会社の上司・部下の関係であろう男女が会話(とは言っても、すべては聞き取れていませんよww)をしていました。部下の方はサミット参加は初めてのようで、すこし緊張した感じ。それを気遣ってか上司は色々丹念にお話を聴いて、アドバイスを与えていました。そして、とにかくいいとこと褒める。これらのことを繰り返ことで部下の方も気分がほぐれていたように見えました。その方とはちょうど同じセッションで緊張した面持ちで質問されていました。上司の方が若干のフォローを入れていましたが見事に質問しきった様子でした。その後も上司の方は絶えずほめて(ように見えただけ、聞きとれないww)いました。( 部下の方、非常にいい経験だっただろうなぁ。 )
 
 山本五十六曰く「やってみせ、言って聞かせて、させてみて、ほめてやらねば、人は動かじ」ですが、やっぱり大事なことですね。ちょっとまじめに語ってしまいましたが、今回は非常にいい経験をさせてもらいました。お世話になった方々にはブログ上でも再度御礼申し上げます。

追伸
 今回のシアトル滞在で書き忘れていたことがありました。それは、Mt.Rainier に行ったこと。
f:id:koogucc11:20161112173027p:plain

 レーニア国立公園に聳え立つ雄大な山です。
f:id:koogucc11:20161112165725j:plain

 山の麓から少し歩くと...
f:id:koogucc11:20161112165734j:plain

 しかも、革靴でww 滑りながらww
f:id:koogucc11:20161112165743j:plain
 
 そして、キレイな滝がありました。帰り道はさらに大変だったことは言うまでもありませんww 
f:id:koogucc11:20161112165754j:plain

 Mt.Rainier への道を少し脇に入ると、そこはもののけ姫の世界。非常に見ごたえがありました。
f:id:koogucc11:20161112165804j:plain

f:id:koogucc11:20161112165814j:plain

 Mt.Rainier は遠くから見てもキレイな山です。
f:id:koogucc11:20161112165822j:plain

スタバ関連買いすぎた気がする....