ログ日記

作業ログと日記とメモ

DBでSQLのテーブル名に別名を付けるときのルールと複数形

データベースのテーブル名を複数形にするかどうか、作るたびに悩む。
Qiita の記事 https://qiita.com/siinai/items/d4274c95fcdde3fd7295 のコメント欄に良いリンクがあった。

SELECT id, name, description FROM products product
WHERE product.name = ‘foo’ AND product.description = ‘bar’
https://medium.com/@fbnlsr/the-table-naming-dilemma-singular-vs-plural-dc260d90aaff


過去に書いた記事*1 を見返していて、そこのリンクにも同じような記事があった。

テーブルに別名を付ける場合、テーブル名の単数形を使用する

SQL の命名規約とフォーマット - ぐるぐる~

Railsとは無関係の文脈だと思うけど、こういう派閥も昔からあったのか。このときは流し読みでスルーしていた。
 
T1 とか tbl_kbn とかは以ての外だけど、この複数形を単数形にする別名のルールは良いかもしれない。

 

SELECT * FROM Customers AS Customer WHERE Customer.FirstName = 'John' - Customers refers to the whole table while Customer refers to the current row.

visual studio - Database tables naming, plural or singular - Stack Overflow

こちらも古いけど複数形テーブルに単数形の別名を付けている。

sql - Table Naming Dilemma: Singular vs. Plural Names - Stack Overflow
こっちは単数形推しで理由がまとまっている。


自分は最初のQiitaの

「テーブル」自体が「複数」そのものではない

テーブルの名前って複数形?単数形? - Qiita

とか
最後のstackoverflowの

Reason 1 (Concept). You can think of bag containing apples like "AppleBag", it doesn't matter if contains 0, 1 or a million apples, it is always the same bag. Tables are just that, containers, the table name must describe what it contains, not how much data it contains. Additionally, the plural concept is more about a spoken language one (actually to determine whether there is one or more).

sql - Table Naming Dilemma: Singular vs. Plural Names - Stack Overflow

とかと同じで単数形にしている。


かと言って複数形にすることは無いかというと、そうでもない。
例えば何らかの理由でファイルに書くようなアプリケーションの設定項目をDBに保存するときは application_settings というただ一つの行のみを持つテーブルを作るかもしれない。
これは the application settings であり、一つの行に複数の設定が詰まっているので意味的に複数形がしっくりくる。行が複数ということではない。

他にも、category_attributesのように何かの情報を詰め込んだ行を持つテーブルは複数形にするかもしれない。
そう考えると全体的に単数形や複数形に統一するという考えとは相反することになりそうだ。