SQL: Update on join, in standards? - sql

I know that most sql server software allows you to do "A Update on a Join", but I am wondering, is this in the SQL standards?
(eg. can I assume that any software package allows this?)
Note: I am asking this because I am writing a database library that should be easily extensible to database software that is not included in the original build. As such there's no point in answering with a remark such as "a, b, c and b all allow that - together they make up the lionshare of the market, so you can assume that all software packages allow that". No, I am interested in whether it is in the standards or not.

If I understand the question right, I think the answer is no, there is no standard "update based on a join". The postgres manual page for UPDATE includes this under "Compatibility":
This command conforms to the SQL standard, except that the FROM and RETURNING clauses are PostgreSQL extensions, as is the ability to use WITH with UPDATE.
Some other database systems offer a FROM option in which the target table is supposed to be listed again within FROM. That is not how PostgreSQL interprets FROM. Be careful when porting applications that use this extension.
While this doesn't explicitly say there isn't, the Compatibility notes in that manual generally note when there is a related, but not identical, feature in the standard. What's more, the mention of other systems with different behaviour demonstrates that if there is a standard, you can't rely on it anyway.

According to the ANSI SQL-92 standard, an UPDATE on JOINed tables is NOT part of the standards; See http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt sections 13.9 and 13.10 (you'll have to search for 391, the page number).
I tried to find an ANSI 2003 standard, but the closest I came was here: www.wiscorp.com/sql_2003_standard.zip (a late draft). There was no substantial difference between the two in regards to the UPDATE statement and JOIN syntax.
Stu

You're presuming that all software packages adhere to ANSI SQL Standards.....in reality, none of them that I'm aware of adhere completely to the standards.
If you're looking to adhere to ANSI SQL standards, the best place to start would be with the documented standards themselves. Here's the SQL-92 document:
http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

Careful now, folks. Writing truly portable code is much more difficult than you would imagine and you also have to be willing to give up a lot in the areas of performance, ease of coding/maintenance, and readability. Just declare and use one variable in, say, SQL Server and your code is no longer truly portable. Write an audit trigger and I can guarantee that your trigger won't be portable between Oracle, SQL Server, and several other popular engines. And, it should really matter because it's not actually rocket science in any RDBMS (well, except maybe for writing a joined UPDATE in Oracle without using MERGE {which is standard but not portable, yet}).
Also, don't forget there are two basic types of SQL. That which supports the single row nature of most front-end code and that of batch code. If you really want your batch code to perform well, you'll use many of the "proprietary extensions" to the database engine you're using to efficiently process sometimes billions of rows overnight... the same night. ;-)
Be careful when aiming at writing code for "true" portability. You might end up with a tangled mess that's a whole lot slower than you might have ever imagined.

Related

Is there a way to make SQL standard compliant queries using Visual Studio?

I just wanted to know if there is an SQL standard compliance validator out there for Visual Studio 2019 Professional (something that could be set to strict: only absolutely compliant syntax would be accepted). It would be nice if it had support for native languages too, but I'm used to that kind of stuff being CLR-only (I don't really know why probably because of linking... I may be so absolutely wrong, though... I actually have no idea and took a guess).
Something important would be that it needs to be standard compliant, not only SQL-server compliant. What is not in the standard is an error.
The goal is to make SQL code that is completely independent of the DBMS. Thank you for taking the time to read my question.
The goal is to make SQL code that is completely independent of the DBMS.
Impossible goal, unless you are going to forsake writing SQL at all. It is perhaps sad, but different databases differ on very fundamental things, picking and choosing the parts of the standard they want. Happily, the major things like SELECT, JOIN and GROUP BY are common but the details are not.
You can think of them of them like dialects of a spoken language over time and region. I'm most familiar with English, but it is true that all languages evolve and change. I can read Shakespearean English, but I am not going to write English like that. It would be grammatically incorrect in some cases, use unknown words, and alternative meanings of common words.
Here are just some examples of some features that differ widely among databases:
Intervals. Adding an interval to a date using the standard syntax is interval + '1 day'. This varies significantly across databases.
Some databases do not support FULL JOIN.
Some databases do not support recursive CTEs. Some use the recursive keyword; some do not.
Some databases do not support the VALUES() constructor in the FROM clause.
Some databases allow the FROM clause to be optional.
The standard has nifty functionality such as FILTER and aggregation by functionally dependent ids.that few databases support
Limitations on data types vary significantly -- what is the longer string, for instance.
The standard uses FETCH to limit results, which some databases do not support.
Parsing strings into dates and formatting dates into strings is totally database-dependent.
Extracting date/time components uses extract() in the standard, but few databases actually support that functionality.
These are just a few of the differences off the top of my head -- in no way meant to be complete or even the most important. I just want to point out that what you want to do is not possible.

Which SQL Implementation can translate to many other(s)?

I'm looking for a SQL Implementation (and its Editor) that can be used for translating it to many other(s) SQL Languages.
For example, when i code in that SQL Language to script file(s), and then i translate to other(s) SQL Language script file(s) (for ex: MS SQL's , MySQL's , ...).
If you're sure to use only ANSI SQL to construct your scripts, you should be good to go.
I agree with #Justin Niessner: all SQL vendors pay attention to the SQL Standards, notably core SQL-92. To take SQL Server as an example, although they find Sybase legacy code is tricky to deprecate they are not afraid to do so and entirely new features (e.g. MERGE in MSSQL2008) tend to extend their Standard SQL equivalents, rather than reinventing the wheel.
For a product that has good Standards compliance, take a look at Mimer
Here at Mimer Information Technology, we pride ourselves on conforming
to the SQL standard and we play an active role in the Database
Languages standardization group which determines exactly what is SQL
standard.
Mimer also provide extremely useful SQL validators for SQL-92, SQL-99 and SQL:2003 respectively.
I've been researching the same thing a while ago. What I've found is that there is a project liquibase. It is aimed at change tracking but also converting between different DBMS. You can download source code and see different datatypes conversions across databases. Source at github browse for java files there, probably you'll find something helpful
If all you want are basic operations, these are fairly universal. For instance:
SELECT
INSERT
DELETE
UPDATE
FROM
WHERE
JOIN
...are all at the most basic level the same across implementations.
However, the more complicated your scripts get, the more difficult it becomes to make them "universal". Things like aggregation, subqueries, cursors, while loops, functions, indexes, constraints, temp tables, variables, string manipulation, window operations etc. are all pretty much database-specific.
Some of these do have "universal" equivalents but the more generic you make your code the worse it will perform.

ANSI SQL Manual

Can anyone recommend a good ANSI SQL reference manual?
I don't necessary mean a tutorial but a proper reference document to lookup when you need either a basic or more in-depth explanation or example.
Currently I am using W3Schools SQL Tutorial and SQL Tutorial which are ok, but I don't find them "deep" enough.
Of course, each major RDBMS producer will have some sort of reference manuals targeting their own product, but they tend to be biased and sometime will use proprietary extensions.
EDITED: The aim of the question was to focus on the things database engines have in common i.e. the SQL roots. But understanding the differences can also be a positive thing - this is quite interesting.
Here's the ‘Second Informal Review Draft’ of SQL:1992, which seems to have been accurate enough for everything I've looked up. 1992 covers most of the stuff routinely used across DBMSs.
SQL isn't like C or Java, where there is a standard for the language, and then a number of companies and organizations are implementing the language as best they can, following the standard.
Instead, the major databases came before the SQL standard, and the standard is a sort of compromise where every database vendor wanted to get their particular dialect and features in the standard.
Therefore, there is much more variety between databases than between typical programming language compilers, and to use a database, you really need to know that particular SQL dialect.
Having said that, I've got Gultzan and Peltzer's SQL-99 Complete, Really here in my bookshelf. It is a good book if you need to know what the standard really contains. (And yes, there is a newer version since SQL-99, but noone seems to care.)
EDIT: Actually, there is not just one newer version since SQL-99, but three: SQL:2003, SQL:2006, and SQL:2008. And still noone seems to care. Actually, many don't even care about SQL-99, so SQL-92 is still, in a way, "the standard".
ANSI documents can all be purchased from -- you guessed it -- ANSI.
http://webstore.ansi.org/
The main problem with an ANSI SQL reference manual is that you can't find a DB which implements it. And when it does, then you'll find that ANSI SQL can't solve some of the daily problems. Which is why all professional databases define extensions.
So at work, you'll need a reference manual for the specific version of the database which you use.
This reminds me of my 2nd year university course where we learn relational theory instead of SQL.
Read a good book on Relational Theory. Database theory and practice have evolved since Edgar Codd originally defined the relational model back in 1969. Independent of any SQL products, SQL and Relational Theory draws on decades of research to present the most up-to-date treatment of the material available anywhere. Anyone with a modest to advanced background in SQL will benefit from the many insights in this book.
Oreilly January 2009
I found the best way to learn SQL was to actually get to writing queries and understanding the nature of joins/conditionals etc. I found this link with a lot of DIY examples to be the best : http://sqlzoo.net/
It's a littel outdated, but this book is really helpful is looking at how the differnt vendors implement things, I belive it includes ANSII standard.
http://www.amazon.com/SQL-Nutshell-2nd-Kevin-Kline/dp/0596004818/ref=sr_1_1?ie=UTF8&s=books&qid=1257963172&sr=8-1
I really like just about anything Joe Celko has written Celko's Books
I think this may be helpful to you.
Understanding the ANSI SQL standard
By: Kevin Kline
http://www.amazon.com/gp/product/1565927443/102-0105946-4028970?v=glance&n=283155
The DevGuru resources always worked well for me:
http://www.devguru.com/technologies/t-sql/home.asp
Although I must admit it's not strictly an 'ANSI' focused resource. I've always been MS SQL centric, and it was helpful to me when I was starting out. IMHO Your best bet will be to use several resources - specifically including at least one of for each DB platform you want to use.
To Quote the DevGuru intro for their T-SQL resource:
Although there are standards for SQL,
such as ANSI SQL92 and SQL99, most
databases use their own dialect and/or
extentions. Microsoft's flavor of SQL
used in SQL Server 7 and SQL Server
2000 is called T-SQL. While many of
the examples in this quick reference
may work on other databases, it is
assumed that SQL Server 2000 is used,
especially for advanced topics such as
stored procedures.

How Important is SQL Portability?

It seems to me, from both personal experience and SO questions and answers, that SQL implementations vary substantially. One of the first issues for SQL questions is: What dbms are you using?
In most cases with SQL there are several ways to structure a given query, even using the same dialect. But I find it interesting that the relative portability of various approaches is frequently not discussed, nor valued very highly when it is.
But even disregarding the likelihood that any given application may or not be subject to conversion, I'd think that we would prefer that our skills, habits, and patterns be as portable as possible.
In your work with SQL, how strongly do you prefer standard SQL syntax? How actively do you eschew propriety variations? Please answer without reference to proprietary preferences for the purpose of perceived better performance, which most would concede is usually a sufficiently legitimate defense.
I vote against standard/vendor independent sql
Only seldom the database is actually switched.
There is no single database that fully conforms to the current sql standard. So even when you are standard conform, you are not vendor independent.
vendor differences go beyond sql syntax. Locking behaviour is different. Isolation levels are different.
database testing is pretty tough and under developed. No need to make it even harder by throwing multiple vendors in the game, if you don't absolutly need it.
there is a lot of power in the vendor specific tweaks. (think 'limit', or 'analytic functions', or 'hints' )
So the quintessence:
- If there is no requirement for vendor independence, get specialised for the vendor you are actually using.
- If there is a requirement for vendor independence make sure that who ever pays the bill, that this will cost money. Make sure you have every single rdbms available for testing. And use it too
- Put every piece of sql in a special layer, which is pluggable, so you can use the power of the database AND work with different vendors
- Only where the difference is a pure question of syntax go with the standard, e.g. using the oracle notation for (outer) joins vs the ANSI standard syntax.
We take it very seriously at our shop. We do not allow non-standard SQL or extensions unless they're supported on ALL of the major platforms. Even then, they're flagged within the code as non-standard and justifications are necessary.
It is not up to the application developer to make their queries run fast, we have a clear separation of duties. The query is to be optimized only by the DBMS itself or the DBAs tuning of the DBMS.
Real databases, like DB2/z :-), process standard SQL plenty fast.
The reason we enforce this is to give the customer choice. They don't like the idea of being locked into a specific vendor any more than we do.
In my experience, query portability turns out to be not so important. We work with various data sources (mainly MSSQL and MySQL), but we know which data is stored where and can optimize accordingly. Since we control the systems, we decide when - if ever - structures are moved and queries need to be rewritten.
I also like to use certain other server-specific functionality, such as query notification in SQL Server, which MySQL doesn't offer. So there, again, we use it when we can and don't worry about portability.
Furthermore, parts of our apps need to query schema information and act on it. Here, again, we have server-specific code for the different systems, instead of trying to restrict ourselves to the lowest common denominator.
There is no clear answer whether SQL portability is desirable or not - it really depends a lot on the situation, such as the type of application.
If the application is going to be a service - ie there will only ever be you hosting it, then obviously nobody but you will care whether your SQL is portable enough, so you could safely ignore it as long as you have no specific plans to drop support for your current platform.
If the application is going to be installed at a number of sites, which each have their own established database systems, obviously SQL portability is very important to people. It lets you widen your potential market, and may give a bit of piece of mind to clients who are on the fence in regards to their database system. Whether you want to support that, or you are happy selling only to, for instance, Oracle customers, or only to MySQL/PostgreSQL customers, for example, is up to you and what you think your market is.
If you are coding in PHP, then the vast majority of your potential customers are probably going to expect MySQL. If so, then it's not a big deal to assume MySQL. Or similarly if you are in C#/.NET then you could assume Microsoft SQL Server. Again, however, there is a flip side because there may exist a small but less competitive market of PHP or .NET users who want to connect to other database systems than the usual.
So I would largely regard this as a market research question, unless as in my first example you are providing a hosted service where it doesn't matter to users, in which case it is for your own convenience only.

Reasons for SQL differences

Why are SQL distributions so non-standard despite an ANSI standard existing for SQL? Are there really that many meaningful differences in the way SQL databases work or is it just the two databases with which I have been working: MS-SQL and PostgreSQL? Why do these differences arise?
The ANSI standard specifies only a limited set of commands and data types. Once you go beyond those, the implementors are on their own. And some very important concepts aren't specified at all, such as auto-incrementing columns. SQLite just picks the first non-null integer, MySQL requires AUTO INCREMENT, PostgreSQL uses sequences, etc. It's a mess, and that's only among the OSS databases! Try getting Oracle, Microsoft, and IBM to collectively decide on a tricky bit of functionality.
It's a form of "Stealth lock-in". Joel goes into great detail here:
http://www.joelonsoftware.com/articles/fog0000000056.html
http://www.joelonsoftware.com/articles/fog0000000052.html
Companies end up tying their business functionality to non-standard or weird unsupported functionality in their implementation, this restricts their ability to move away from their vendor to a competitor.
On the other hand, it's pretty short-sighted because anyone with half a brain will tend to abstract away the proprietary pieces, or avoid the lock-in altogether, if it gets too egregious.
First, I don't find databases to be as, say, browsers or operating systems in terms of incompatibility. Anyone with a few hours of training can start doing selects, inserts, deletes and updates on any SQL database. Meanwhile, it's difficult to write HTML that renders identically on every browser or write system code for more than one OS. Generally, differences in SQL are related to performance or fairly esoteric features. The major exception seems to be date formats and functions.
Second, database developers generally are motivated to add features that differentiate their product from everyone else. Products like Oracle, MS SQL Server and MySQL are vast ecosystems that rarely cross-pollinate in practice. At my workplace, we use Oracle and MySQL, but we could probably switch over to 100% Oracle in about a day if needed or desired. So I care a lot about the shiny toys Oracle gives us with each release, but I don't even know what version of MySQL we are using. IBM, Microsoft, PostgreSQL and the rest might as well not exist as far as we are concerned. Having the features to get and keep customers and users is far more important than compatibility in the database world. (That's the positive spin on the "lock-in" answer, I suppose.)
Third, there are legitimate reasons for different companies to implement SQL differently. For instance, Oracle has a multi-versioning system that allows very fast and scalable consistent reads. Other databases lack that feature, but usually are faster inserting rows and rolling back transactions. This is a fundamental difference in these systems. It doesn't make one better than the other (at least in the general case), just different. One should not be surprised if the SQL ontop of a database engine takes advantage of its strengths and attempts to minimize its weaknesses. In fact, it would be irresponsible of the developers to not do this.
John: The standard actually covers lots of subjects, including identity columns, sequences, triggers, routines, upsert, etc. But of course, many of these standards-components may have been brought in place later than the first implementations; and this could be a reason why SQL standards compliance is somewhat low, generally.
Neall: There are actually areas where the SQL standard is ahead of the implementations. For example, it would be nice to have CREATE ASSERTION, but as far as I know, no DBMS implements assertions yet.
Personally, I believe that the closed nature of some ISO standards (like the SQL standard) is part of the problem: When a standard is not readily available online, it's less likely to be known by implementors/planners, and too few customers ask for compliance because they don't know what to ask for.
It's certainly effective lock-in, as 1800 says. But in fairness to the database vendors, the SQL standard is always playing catch-up to current databases' feature sets. Most databases we have today are of pretty ancient lineages. If you trace Microsoft SQL Server back to its roots, I think you'll find Ingres - one of the very first relational databases written in the '70s. And Postgres was originally written by some of the same people in the '80s as a successor to Ingres. Oracle goes way back, and I'm not sure where MySQL came in.
Database non-portability does suck, but it could be a lot worse.