Referencing tables - sql-server

In SQL Server, why is this:
[dbo].[table_name]
preferable to this:
dbo.table_name
And along those lines, why even list the dbo at all if there's only one schema?

If the table name contains key words, you will have to enclose it inside [ ]. Most of the tools (like ORM) use this technique to avoid any errors or for consistency.

It's just in case you have a keyword as a tablename like [user]

It allows keywords or punctuation in a table name.
It's often used by code generators for all names, so they don't have to figure out if it actually needed.

These usually come up in generated code - because it's easier to make the code generation produce fully-qualified and escaped references than to deduce what escaping/qualification is required when.

If there is only one schema then prefixing the table name is not necessary or useful I think. Using the brackets [] is useful when you have an identifier that is a reserved word in sql server. If, for instance, you have a table named Select you can refernce it as SELECT * FROM [Select] but not as SELECT * FROM Select.

I don't use the brackets, which are only necessary if you use keywords as schemas or table names, which you shouldn't.
But I would recommend against dropping the dbo at the front. The reason is that eventually you might want to start organizing your code into schemas, and then you will need the prefix. If you get in the habit of using the schema.table format, it will be a lot easier to search your code for places where the tables are used.
Let's say you have a table called dbo.user, and you decide to move it to another schema. If you have to search through a bunch of stored procedures or dynamic sql for "user", you will likely get a ton of false positives. You can't be totally sure that you made all the changes you needed to. Searching for "dbo.user" is a lot more concise.

The [] are only required if the object name contains characters like spaces or if it is a keyword. It is generally regarded as best practice not to use any of these as object names so you should never need the []. Having said that they also do no harm, if it is generated code and includes the brackets then you may as well leave them.
Using dbo is a good idea becuase
Performance is better (see here for some figures)
dbo is required in some cases, like calling user defined functions. I think it is tidyer to always include it.
Not qualifying the object name could lead to bugs in the future if you do create multiple schemas.

Doesn't this allow you to have whatever 'bad' items you desire in there?
Keywords, spaces, etc...

I would prefer to avoid using punctuation and reserved words in table and column names, and not use the square brackets. This makes the SQL far easier to read.

Apart from spaces, reserved keywords, and system functions in an identifier name, an identifier can also contain some characters that are not allowed in regular identifiers, an it has to be separated with square brackets.
You can find a detailed explanation and rules for regular and delimited identifiers in this article.
From the article:
For example, delimited identifiers can contain spaces, any characters
valid for regular identifiers, and any one of the following
characters:
tilde (~) hyphen, (-) exclamation point (!), left brace ({), percent (%),
right brace (}), caret (^), apostrophe ('), ampersand (&), period (.), left
parenthesis ((), backslash (), right parenthesis ()), accent grave (`),
Using two name qualifying convention may improve performance (avoid name resolutions) and avoid ambiguity in cases when you have e.g. the same table name in two or more schema. In that case SQL Server will search your object in dbo and if it isn't there it will stop searching.
Also if you later want to use that object with the SCHEMABINDING option it doesn't allow unqualified object names.
Hope this helps

Related

How do I escape reserved words used as identifier in Netezza

One can use delimited identifier in JDBC query and it works with below databases even for a non reserved keyword with below delimiters:
SQLServer: Square bracket => [select]
Postgres, Teradata, Oracle, Sybase and DB2: double quote => "select"
For Netezza I tried single quote as per documentation, but it did not work.
https://www.ibm.com/support/knowledgecenter/en/SSULQD_7.2.1/com.ibm.nz.dbu.doc/c_dbuser_quoted_mixed_literals.html
Please suggest.
What works at my site is the " (double quotes) around table/column names containing reserved words, spaces, special/national characters, numbers at the beginning and many other things a good data model does not contain (opinion - I know, but a heart felt one)
You need to be aware that anything referenced using "surrounding", becomes cAsE sensitive.
Try querying the catalog view INFORMATION_SCHEMA.COLUMNS using your favorite sql-client (aginity?) and look carefully at the caSiNg etc of the names of the columns/table you try to reference.
Hope this helps - otherwise please post a simple piece of sql that you would expect to succeed, along with the error message you got back, just as ScottMcG suggested

How to make oracle installation case sensitive?

I have oracle express installation, and by default it is case insensitive ( table creation/ keys name ). I want to change it to case sensitive. Is there a configuration to do so?
There is no setting, no.
In any version of Oracle, however, you can use case-sensitive identifiers by enclosing them in double-quotes.
create table "CamelCase" (
"ColumnName1" integer
);
will create a table CamelCase which is case-sensitive and a column ColumnName1 that is case sensitive. In order to use the column, though, every reference will need to be surrounded in double-quotes
SELECT "ColumnName1"
FROM "CamelCase"
would work. However
SELECT ColumnName1
FROM CamelCase
would not.
Using case-sensitive identifiers is generally a really bad idea so I would strongly suggest that you don't do so. It is an option though.
No, there is no configuration for that. You can't make identifiers case-sensitive without quoting them, but Oracle recommends against using quoted identifiers:.
Oracle does not recommend using quoted identifiers for database object names. These quoted identifiers are accepted by SQL*Plus, but they may not be valid when using other tools that manage database objects.
And even then if you have a quoted identifier that is all-caps anyway, e.g. "MY_TABLE", that is treated the same as an unquoted identifier so you can still refer to it as my_table, which might not be case-sensitive enough for you. Anything mixed-case or with invalid characters always has to be referred to quoted though, e.g. `select * from "My Table", which makes code harder to read and maintain (in my opinion anyway).
I'd really recommend not doing this. Anyone having to maintain your schema or code will not thank you for it.

Oracle - Table names and columns - could I change the casing?

By default - Are all oracle table names and columns stored in uppercase?
Could I change to casing?
In the data dictionary, yes, identifiers are converted to upper case by default.
You can change that behavior by creating case-sensitive identifiers. It is generally not a good idea to do so, but you can. In order to do so, you would need to enclose the table name and column names in double quotes both when you create the object and every time you want to refer to them. You'll also need to get the casing right because the identifiers will be case-sensitive unlike the normal case-insensitive behavior.
If you
CREATE TABLE "foo" (
"MyMixedCaseColumn" number
);
then the table name and column name will be stored in mixed case in the data dictionary. You'll need to use double-quotes to refer to either identifier in the future. So
SELECT "MyMixedCaseColumn"
FROM "foo"
will work. However, something like
SELECT MyMixedCaseColumn
FROM foo
will not. Nor will
SELECT "MyMixedCaseColumn"
FROM "Foo"
Generally, future developers will be grateful if you don't use case-sensitive identifiers. It's annoying to have to use double-quotes all over the place and not every tool or library has been tested against systems that use case-sensitive identifiers so it's not uncommon for things to break.

Is there any reason to write a database column between square brackets?

I am maintaining a database created by another person in SQL Server. In one table I found a column whose name is between square brackets. The name of the field is desc and it is stored in the table as [desc]. The other fields are stored without square brackets. Is there any special reason/convention behind this choice?
The applications built on top of the Database are developed either in C# or VB.NET.
Thanks
The brackets (or other identifiers in other database engines) are just an explicit way of telling the query engine that this term is an identifier for an object in the database. Common reasons include:
Object names which contain spaces would otherwise fail to parse as part of the query unless they're wrapped in brackets.
Object names which are reserved words can fail to parse (or, worse, correctly parse and do unexpected things).
(I suppose it's also possible that there may be an ever-so-slight performance improvement since the engine doesn't need to try to identify what that item means, it's been explicitly told that it's an object. It still needs to validate that, of course, but it may be a small help in the inner workings.)
If your names contains either a reserved word (such as SELECT) or spaces, then you need to surround the name with [].
In your example, you have [desc], which is short for DESCENDING.
For example if you have a field that is a keyword e.g [Date] or [Select] or in this case [desc]

What is the use of the square brackets [] in sql statements?

I've noticed that Visual Studio 2008 is placing square brackets around column names in sql. Do the brackets offer any advantage? When I hand code T-SQL I've never bothered with them.
Example:
Visual Studio:
SELECT [column1], [column2] etc...
My own way:
SELECT column1, column2 etc...
The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space) – but then you'd need to use brackets every time you referred to that column.
The newer tools add them everywhere just in case or for consistency.
They're handy if your columns have the same names as SQL keywords, or have spaces in them.
Example:
create table test ( id int, user varchar(20) )
Oh no! Incorrect syntax near the keyword 'user'.
But this:
create table test ( id int, [user] varchar(20) )
Works fine.
They are useful if you are (for some reason) using column names with certain characters for example.
Select First Name From People
would not work, but putting square brackets around the column name would work
Select [First Name] From People
In short, it's a way of explicitly declaring a object name; column, table, database, user or server.
During the dark ages of SQL in the 1990s it was a good practice as the SQL designers were trying to add each word in the dictionary as keyword for endless avalanche of new features and they called it the SQL3 draft.
So it keeps forward compatibility.
And i found that it has another nice side effect, it helps a lot when you use grep in code reviews and refactoring.
Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....
Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named #String and a column named [String], you can rename the column to [NewString], without renaming #String to #NewString.
Column names can contain characters and reserved words that will confuse the query execution engine, so placing brackets around them at all times prevents this from happening. Easier than checking for an issue and then dealing with it, I guess.
The brackets can be used when column names are reserved words.
If you are programatically generating the SQL statement from a collection of column names you don't control, then you can avoid problems by always using the brackets.
In addition
Some Sharepoint databases contain hyphens in their names. Using square brackets in SQL Statements allow the names to be parsed correctly.
They are useful to identify each elements in SQL.
For example:
CREATE TABLE SchemaName.TableName (
This would actually create a table by the name SchemaName.TableName under default dbo schema even though the intention might be to create the table inside the SchemaName schema.
The correct way would be the following:
CREATE TABLE [SchemaName].[TableName] (
Now it it knows what is the table name and in which schema should it be created in (rightly in the SchemaName schema and not in the default dbo schema)
I believe it adds them there for consistency... they're only required when you have a space or special character in the column name, but it's cleaner to just include them all the time when the IDE generates SQL.

Resources