`
jake0719
  • 浏览: 90351 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

SQL Naming Convention

阅读更多

突然发现创建数据库没有统一的命名规范. 下面一篇文章不错可以参考, 另外还可以参考MSDN-Oslo的表设计模式.:

The following list provides the SQL guidelines for designing tables for the “Oslo” repository.

  1. Create Tables to Store Entity Instances of a Data Model.
  2. Create a Primary Key Named Id.
  3. Add a Folder Column to Support the “Oslo” Repository Folder Design Pattern.
  4. Use Foreign Keys to Connect Related Tables within a Data Model.
  5. Consider Performance Implications of Table Design Choices.
  6. Restrict Access to Base Tables to the RepositoryAdministrator and RepositoryService Users.
  7. Add a timestamp Column for Use with Lifetime Services.
  8. Follow “Oslo” Repository Design Patterns for the Localization of Strings and Resources.

SQL Naming Convention

转自:http://kurafire.net/articles/sql-convention

 

There are millions of people making applications that use some sort of database or another, and there are several dozens of conventions which you can use to make a more well-formed database schematic. The CMS that powers this website is written by a semi-selfmade SQL convention. This article explains how it works.

The Media Design Content Management System, which is what I use to create and manage this website, uses PostgreSQL as its database system, rather than the more well-known MySQL.

For those of you that don't know, SQL stands for Structured Query Language, and is pronounced as [es queue el] (and not as sequal, as that name had caused trademark conflicts 18 years ago). There are various database systems that are based on SQL standards, although all of them have their own extentions to the official SQL Standard. If you want to read more about SQL, see this Wikipedia page on SQL. This article focuses only on PostgreSQL and this CMS's implementation using it.

Before we get started, we should look at what a standard or convention generally requires: consistency. You can make a standard without a lot of consistency (see RSS for example), but then it probably won't be a very good or useful standard. And as it is consistency and logic that determine a lot of the quality of a product or standard, it is consistency and logic that should be a major focus point of a naming convention.

Our CMS's Convention

Short and descriptive

At all times, stick to using as short as possible database-, table- and column names, but not at the cost of descriptiveness. Make sure that one look at the name can explain the purpose and content of the table or column.

Examples: filename, title, moderated, dateline.

Underscores are evil

Using underscores between words generally means your table or column names are not short and descriptive enough. There really is little need to have columns like user_name when username works just fine. Not only is the latter shorter, but it is also better: sometimes you'll have a column name that is valid as two words but also as one word, and then people may come to expect it as one word only to find out you treated it as two and put an unexpected underscore in-between. If you're the only person that will ever, ever touch your database system and your code… you should still stay away from underscores. You don't know what the future brings. Stick to consistency, and consistency can only be achieved here by not using underscores in table and column names.

Say no to CamelCase

CamelCase is an often adopted naming convention, used mainly in programming languages like Java and JavaScript. Its principle is simple: start every new word with a capital letter: camelCase, myObject, someFunction, etc. But CamelCase, or any uppercase in general, is not recommended for table and column names in SQL. Why, you wonder? Well, SQL databases tend to convert all identifiers (table/column names) to lowercase unless you wrap them in quotes. So even though you create a table called Authors, it'll be made as authors. Then, if you somehow end up moving your database to a server where the SQL system is compiled to be case-sensitive, and your code has Authors everywhere, it won't work anymore. Additionally, exporting your database scheme and moving it from Windows to Linux using certain tools comes at the risk that your names will all be lowercased along the way, which will - again - make your code (with CamelCase in it) stop working. Or imagine you have a column called authorId. The capital I for id can easily look like a lowercase L in many fonts, adding to the risk of confusing other people who have to work with your code. There are just too many small risks involved in using CamelCase, so try to avoid it and stick to lowercase.

Table names in column names

Certain conventions dictate that you use {tablename}_{columnname}, ie. table author would have author_name, author_birthday and so forth. Our suggestion: don't do that. A table is a collection of columns that belong in it, and a column name is exactly what it says: a column name; not a "column identifier with a table identifier in it as well". Stick to columnname; not only is it much shorter, it also does not require underscores nor does it clutter up queries unnecessarily. For instance, compare these two queries:

  1. SELECT post_title AS title, post_content AS content, post_dateline AS dateline, post_author_id AS author_id FROM post;
  2. SELECT title, content, dateline, authorid FROM post;

Which is easier to read? The second, as it keeps all data clean and easy to scan.

Furthermore, there are other reasons to stay away from using table names in column names (besides being illogical in their presence): what would happen if you had a table called post that would, later on in development of the application, start to conflict with something else? What if you had to rename it to entry? You'd end up with table entry and a bunch of columns that are prefixed with post_. Now you'll be stuck with highly inconsistent naming, or you have to go through all of your code and not only update the table name, but all of your column names as well! That can easily become quite tedious, as you can probably imagine.

And that's still not the end of it! Aside of being illogical, cluttersome, space-consuming and hardly future-proof, they also make it harder to join tables in queries. You can say that in a way it makes it easier, because you'll never have to worry about ambiguity in column names, but you're removing the use of USING() and you're making JOIN queries look very complicated, even when they're not. What's worse, some people make queries such as this:

SELECT post_title AS title, post_dateline AS dateline, 
author_name AS name FROM post LEFT JOIN author 
ON (post_author_id = author_id)

Why is that so bad?

SELECT title, dateline, name FROM post 
LEFT JOIN author USING (authorid)

…is simply much cleaner and easier to scan.

And to top it all off, using table names in your column names will only make matters highly confusing once you start having columns that reference columns on other tables. You'll end up with a column like this: post_link_id. That's 2 table names in a single column name. Not exaclty desirable, I would say.

There is one example where this is justifiable, see ID Columns below.

Avoid reserved keywords!

Tools such as phpMyAdmin allow you to name your tables and columns whatever you want, even when the names you choose are actually reserved keywords. That's because MySQL allows you to create such tables, but requires them enclosed in backticks (`). Using reserved keywords is very risky; you'll be forced to always use backticks (this is MySQL-specific, by the way) and if you forget them anywhere at all, you'll run into problems. Additionally, if your dump of the database(s) or table(s) is made without backticks, you'll have to manually add them because otherwise restoring the dump won't work. Be smart; just avoid using them at all times. They're never a necessity.

ID columns

Also known as auto_increment or serial columns, these are usually the very first column on any table and are almost always the Primary Key column of the table. For ID columns, you can choose to name them all id or, what we adopted for the Media Design CMS, {tablename}id (avoiding underscores). Having been completely consistent in the design of the database and all of its tables, we've been able to simplify a lot of functions and methods around this, making our life much easier. Whenever we need a serial (PostgreSQL's version of the ID column), we know it's found at tablename + 'id'. This makes referencing, joining and simply querying a lot easier. Additionally, by going for a tablename + 'id' instead of just 'id' we can always see from every serial and in every JOIN query what table it is for. Doing this for all columns, though, is overkill.

That sums up the rough convention used for the database scheme of our CMS. It may not be the "end-all, be-all" convention, but it's logical, consistent (providing you accept the good reasons to break one consistency rule) and works very nicely.

分享到:
评论

相关推荐

    Microsoft SQL 2007年认证试题(英文PDF版)

    When you add SQL2 as a linked server to SQL1, you can reference tables and views on SQL2 directly from SQL1 using the four-part naming convention (linked_server.database.schema.table). - **Remote ...

    PowerDesinger设置集锦.docx

    在 PowerDesigner 中,可以通过修改 Model Options 中的 Naming Convention 来去除 sql 语句中的引号。在 Tools 菜单栏中找到 Model Options,选择 Naming Convention,将 Name 和 Code 的标签的 Character case ...

    关于SQL注入中文件读写的方法总结

    此外,还可以通过UNC路径(Universal Naming Convention)读取其他主机上的文件,如SELECT load_file('//ecma.io/1.txt')。这种文件读取方式在DNS隧道攻击中尤其有用。 对于写文件,文章介绍了两种方法。使用INTO ...

    PowerDesigner使用

    - 在CDM模式下,通过`Tools - Model Options - Naming Convention`,将`Name`和`Code`标签下的`Charcter case`选项设为`Uppercase`或`Lowercase`。 - 通过`Database -> Edit current database -> Script -> Sql -> ...

    清华大学Oracle(ppt)培训资料

    2. 命名规范(Naming Convention):统一数据库对象的命名规则,提高代码可读性。 3. 索引策略(Index Strategy):根据查询模式合理创建索引,避免过度索引。 4. 触发器与约束(Triggers and Constraints):通过...

    matlab尺度变换代码-EmotionMap:在全球范围内使用几种不同的数据源探索情绪分布

    matlab尺度变换代码 EmotionMap 情绪地图 Explore the emotion distribution with several different ...Naming convention ...SQL语句所有SQL语法单词均大写,具体的变量名均小写。 例如:SELECT * FROM tabl

    PowerDesigner常见问题.doc

    - **进入** `Tools -> Model Options -> Naming Convention`; - **设置** `Name` 和 `Code` 标签下的 `Character Case` 选项为 `Uppercase` 或 `Lowercase`(而非 `MixedCase`)。 2. **通过脚本格式设置:** -...

    PowerDesigner操作手册

    一是“Tools-Model Options-Naming Convention”中设置Name和Code的Character case为Uppercase或Lowercase;二是“Database->Edit current database->Script->Sql->Format”,将CaseSensitivityUsingQuote设为"No...

    abap基础培训笔记

    8. **Naming Convention**: 在ABAP中创建自定义对象时,一般以`Z`或`Y`开头以区分标准对象。 9. **Appending Structures**: 可以在现有表上附加结构,但需谨慎操作,不是所有表都支持增强。 10. **Type Group**: ...

    PowerDesigner一些小技巧

    如果希望在建表脚本中去掉对象的双引号,可以在CDM或PDM下,通过Tools -> Model Options -> Naming Convention设置Name和Code的Character Case为Uppercase或Lowercase,避免Mixed Case。另一种方式是在Database -> ...

    access建立网页数据库.pdf

    10. UNC (Uniform Naming Convention): UNC是一种用于识别网络上共享资源的命名规则,它通过指定网络路径来访问服务器上的文件或资源。 11. HTTP (HyperText Transfer Protocol): HTTP是用于从Web服务器传输超文本...

    PowerDesinger使用小技巧定义.pdf

    - 当你在SQL语句中遇到表名和字段名被引号包围导致大小写敏感问题时,可以在`Tools`菜单下选择`Model Options`,然后在`Naming Convention`选项中,调整`Name`和`Code`的`Character Case`设置为`Uppercase`或`...

    PowerDesigner 设置

    打开 cdm 的情况下,进入 Tools-Model Options-Naming Convention,把 Name 和 Code 的标签的 Charcter case 选项设置成 Uppercase 或者 Lowercase,只要不是 Mixed Case 就行! 或者选择 Database->Edit current...

    PowerDesigner用法

    用户可以通过`Tools -> General Options -> Dialog -> Name to code mirroring`以及`Tools -> Mode Options -> Naming Convention`路径,取消“Enable name/code conversions”选项,以避免不必要的名称转换。...

    Powerdesigner使用建议(完整版) 用实体关系图进行数据库建模

    通过“Tools”菜单下的“Model Options”,可以进入“Naming Convention”设置页面,选择“Name Code”标签页,用户能够指定字符大小写规则,如全部大写(Uppercase)、全部小写(Lowercase)或混合大小写(Mixed Case)。...

    power designer心得

    - 为了保持模型的一致性,可以通过`Tools -> Model Options -> Naming Convention -> Name Code`来设置字符大小写规则,例如选择全部大写或小写,以确保生成的数据库对象名格式统一。 - 在`Database -> Edit ...

    java读取局域网共享机器文件

    1. **网络路径表示**:Java中,网络路径通常以UNC(Universal Naming Convention)格式表示,形如`\\hostname\shared_directory\file.txt`。这里`hostname`是共享机器的名称,`shared_directory`是共享目录,`file....

    Agile Web Development with Rails Final

    By adhering to specific conventions, Rails automatically handles many aspects of application setup, such as database schema, directory structures, and file naming conventions. This approach reduces ...

    java术语 it术语

    #### Convention 约定是指在软件开发过程中遵循的一套规则或最佳实践。这些约定有助于提高代码的可读性和一致性,便于团队协作。 #### CORBA (Common Object Request Broker Architecture) 公共对象请求代理体系...

Global site tag (gtag.js) - Google Analytics