Sql Server Moving Average Funktion


SQL-Funktionen SQL-Funktionen sind in die Oracle-Datenbank integriert und stehen für verschiedene SQL-Anweisungen zur Verfügung. Verwechseln Sie nicht SQL-Funktionen mit benutzerdefinierten Funktionen, die in PLSQL geschrieben sind. Wenn Sie eine SQL-Funktion mit einem Argument eines anderen Datentyps als dem von der SQL-Funktion erwarteten Datentyp aufrufen, versucht Oracle, das Argument vor der Ausführung der SQL-Funktion in den erwarteten Datentyp zu konvertieren. Wenn Sie eine SQL-Funktion mit einem Null-Argument aufrufen, gibt die SQL-Funktion automatisch Null zurück. Die einzigen SQL-Funktionen, die nicht unbedingt diesem Verhalten folgen, sind CONCAT. NVL. ERSETZEN. Und REGEXPREPLACE. Die kombinierten Werte der NLSCOMP - und NLSSORT-Einstellungen bestimmen die Regeln, nach denen Zeichen sortiert und verglichen werden. Wenn NLSCOMP auf LINGUISTIC für Ihre Datenbank gesetzt ist, werden alle Entitäten in diesem Kapitel entsprechend den vom NLSSORT-Parameter angegebenen Regeln interpretiert. Wenn NLSCOMP nicht auf LINGUISTIC gesetzt ist. Dann werden die Funktionen ohne Rücksicht auf die NLSSORT-Einstellung interpretiert. NLSSORT kann explizit gesetzt werden. Wenn es nicht explizit gesetzt ist, wird es von NLSLANGUAGE abgeleitet. Weitere Informationen zu diesen Einstellungen finden Sie im Oracle Database Globalization Support Guide. In den Syntaxdiagrammen für SQL-Funktionen werden Argumente durch ihre Datentypen angezeigt. Wenn die Parameterfunktion in der SQL-Syntax erscheint, ersetzen Sie sie durch eine der in diesem Abschnitt beschriebenen Funktionen. Funktionen werden nach den Datentypen ihrer Argumente und deren Rückgabewerte gruppiert. Wenn Sie SQL-Funktionen auf LOB-Spalten anwenden, erstellt Oracle Database temporäre LOBs während der SQL - und PLSQL-Verarbeitung. Sie sollten sicherstellen, dass das temporäre Tablespace-Kontingent ausreichend ist, um diese temporären LOBs für Ihre Anwendung zu speichern. Benutzerdefinierte Funktionen für Informationen zu Benutzerfunktionen und Datenkonvertierung für die implizite Konvertierung von Datentypen Oracle Textreferenz für Informationen zu Funktionen, die mit Oracle Text verwendet werden Oracle Data Mining Anwendungsentwicklerhandbuch für Informationen zu häufigen Itemsetfunktionen, die mit Oracle Data Mining verwendet werden Die Syntax, die die Kategorien enthält Der Funktionen folgt: In den folgenden Abschnitten werden die integrierten SQL-Funktionen in jeder der in den vorangegangenen Diagrammen dargestellten Gruppen mit Ausnahme benutzerdefinierter Funktionen aufgelistet. Sämtliche eingebauten SQL-Funktionen werden dann in alphabetischer Reihenfolge beschrieben. Einzeilige Funktionen Einzeilige Funktionen geben eine einzelne Ergebniszeile für jede Zeile einer abgefragten Tabelle oder Sicht zurück. Diese Funktionen können in Auswahllisten, WHERE-Klauseln, START WITH - und CONNECT BY-Klauseln und HAVING-Klauseln erscheinen. Numerische Funktionen Numerische Funktionen erlauben numerische Eingabe und geben numerische Werte zurück. Die meisten numerischen Funktionen, die NUMBER-Werte zurückgeben, die auf 38 Dezimalstellen genau sind. Die transzendentalen Funktionen COS. EXP. LN. LOG. SÜNDE. SinH SQRT. BRÄUNEN. Und TANH sind genau auf 36 Dezimalstellen genau. Die transzendentalen Funktionen ACOS. WIE IN. EINE LOHE. Und ATAN2 sind bis zu 30 Dezimalstellen genau. Die numerischen Funktionen sind: Zeichenfunktionen Rückgabe von Zeichenwerten Zeichenfunktionen, die Zeichenwerte zurückgeben, geben Werte der folgenden Datentypen zurück, wenn nicht anders dokumentiert: Wenn das Eingabeargument CHAR oder VARCHAR2 ist. Dann ist der zurückgegebene Wert VARCHAR2. Wenn das Eingabeargument NCHAR oder NVARCHAR2 ist. Dann ist der zurückgegebene Wert NVARCHAR2. Die Länge des von der Funktion zurückgegebenen Wertes wird durch die maximale Länge des zurückgegebenen Datentyps begrenzt. Für Funktionen, die CHAR oder VARCHAR2 zurückgeben. Wenn die Länge des Rückgabewertes den Grenzwert überschreitet, schneidet Oracle Database es ab und gibt das Ergebnis ohne Fehlermeldung zurück. Für Funktionen, die CLOB-Werte zurückgeben, wenn die Länge der Rückgabewerte den Grenzwert überschreitet, wirft Oracle einen Fehler auf und gibt keine Daten zurück. Die Zeichenfunktionen, die Zeichenwerte zurückgeben, sind: NLS-Zeichenfunktionen Die NLS-Zeichenfunktionen geben Informationen über den Zeichensatz zurück. Die NLS-Zeichenfunktionen sind: Zeichenfunktionen Rückgabe von Zahlenwerten Zeichenfunktionen, die Zahlenwerte zurückgeben, können als Argument einen beliebigen Zeichendatentyp verwenden. Die Zeichenfunktionen, die Zahlenwerte zurückgeben, sind: Datetime-Funktionen Datetime-Funktionen arbeiten mit Datum (DATE), Zeitstempel (TIMESTAMP. TIMESTAMP MIT ZEITZONE) und Intervall (INTERVAL DAY TO SECOND INTERVAL YEAR TO MONTH) Werte. Einige Datetime-Funktionen wurden für den Datentyp Oracle DATE (ADDMONTHS, CURRENTDATE, LASTDAY, NEWTIME und NEXTDAY) entwickelt. Wenn Sie als Argument einen Zeitstempelwert angeben, konvertiert Oracle Database den Eingabetyp intern in einen DATE-Wert und gibt einen DATE-Wert zurück. Die Ausnahmen sind die MONTHSBETWEEN-Funktion, die eine Zahl zurückgibt, und die ROUND - und TRUNC-Funktionen, die keine Zeitstempel - oder Intervallwerte akzeptieren. Die verbleibenden Datetime-Funktionen wurden entworfen, um einen der drei Datentypen (Datum, Zeitstempel und Intervall) zu akzeptieren und einen Wert von einem dieser Typen zurückzugeben. Die Datetime-Funktionen sind: Allgemeine Vergleichsfunktionen Die allgemeinen Vergleichsfunktionen bestimmen den größten und / oder niedrigsten Wert aus einem Satz von Werten. Die allgemeinen Vergleichsfunktionen sind: Konvertierungsfunktionen Konvertierungsfunktionen konvertieren einen Wert von einem Datentyp in einen anderen. Im Allgemeinen folgt die Form der Funktionsnamen dem Konvention Datentyp TO Datentyp. Der erste Datentyp ist der Eingabedatentyp. Der zweite Datentyp ist der Ausgabedatentyp. Die SQL-Konvertierungsfunktionen sind: Große Objektfunktionen Die großen Objektfunktionen arbeiten auf LOBs. Die großen Objektfunktionen sind: Erfassungsfunktionen Die Erfassungsfunktionen funktionieren auf verschachtelten Tabellen und Variablen. Die SQL-Auflistungsfunktionen sind: Hierarchische Funktion Die hierarchische Funktion wendet hierarchische Pfadinformationen auf eine Ergebnismenge an. Data Mining-Funktionen Die Data-Mining-Funktionen basieren auf Modellen, die mit dem DBMSDATAMINING-Paket oder der Oracle Data Mining-Java-API erstellt wurden. Die SQL-Data-Mining-Funktionen sind: XML-Funktionen Die XML-Funktionen funktionieren oder liefern XML-Dokumente oder Fragmente zurück. Weitere Informationen zum Auswählen und Abfragen von XML-Daten mit diesen Funktionen, einschließlich Informationen zur Formatierungsausgabe, finden Sie im Oracle XML DB Developers Guide. Die SQL-XML-Funktionen sind: Codierung und Decodierung Funktionen Die Codierung und Decodierung Funktionen können Sie inspizieren und decodieren Daten in der Datenbank. NULL-verwandte Funktionen Die NULL-bezogenen Funktionen ermöglichen eine Nullhandhabung. Die NULL-bezogenen Funktionen sind: Umgebungs - und Identifikatorfunktionen Die Umgebungs - und Identifikationsfunktionen enthalten Informationen über die Instanz und Sitzung. Diese Funktionen sind: Aggregatfunktionen Aggregatfunktionen liefern eine einzelne Ergebniszeile basierend auf Gruppen von Zeilen und nicht auf einzelnen Zeilen. Aggregatfunktionen können in Auswahllisten und in ORDER BY - und HAVING-Klauseln erscheinen. Sie werden häufig mit der GROUP BY-Klausel in einer SELECT-Anweisung verwendet, wobei Oracle Database die Zeilen einer abgefragten Tabelle oder Sicht in Gruppen unterteilt. In einer Abfrage, die eine GROUP BY-Klausel enthält, können die Elemente der Auswahlliste Aggregatfunktionen, GROUP BY-Ausdrücke, Konstanten oder Ausdrücke mit einer dieser sein. Oracle wendet die Aggregatfunktionen auf jede Gruppe von Zeilen an und gibt eine einzelne Ergebniszeile für jede Gruppe zurück. Wenn Sie die GROUP BY-Klausel weglassen, wendet Oracle Aggregatfunktionen in der Auswahlliste auf alle Zeilen in der abgefragten Tabelle oder Sicht an. Sie verwenden Aggregatfunktionen in der HAVING-Klausel, um Gruppen aus der Ausgabe zu eliminieren, basierend auf den Ergebnissen der Aggregatfunktionen und nicht auf den Werten der einzelnen Zeilen der abgefragten Tabelle oder View. Verwenden der GROUP BY-Klausel: Beispiele und die HAVING-Klausel für weitere Informationen über die GROUP BY-Klausel und HAVING-Klauseln in Abfragen und Unterabfragen Viele (aber nicht alle) Aggregatfunktionen, die ein einziges Argument akzeptieren, akzeptieren diese Klauseln: DISTINCT bewirkt eine Aggregatfunktion Nur bestimmte Werte des Argumentausdrucks. ALLE bewirkt, dass eine Aggregatfunktion alle Werte berücksichtigt, einschließlich aller Duplikate. Zum Beispiel ist der DISTINCT-Durchschnitt von 1, 1, 1 und 3 2. Der ALL-Durchschnitt ist 1,5. Wenn Sie keinen Wert angeben, ist der Standardwert ALL. Alle Aggregatfunktionen außer COUNT () und GROUPING ignorieren Nullwerte. Sie können die NVL-Funktion im Argument einer Aggregatfunktion verwenden, um einen Wert für einen Nullwert zu ersetzen. COUNT gibt niemals null zurück, sondern gibt entweder eine Zahl oder Null zurück. Für alle übrigen Aggregatfunktionen, wenn der Datensatz keine Zeilen enthält oder nur Zeilen mit Nullen als Argumente für die Aggregatfunktion enthält, gibt die Funktion null zurück. Die Aggregatfunktionen MIN. MAX. SUMME. AVG. GRAF. VARIANZ. Und STDDEV. Wenn es von dem Schlüsselwort KEEP gefolgt wird, kann in Verbindung mit der FIRST - oder der LAST-Funktion verwendet werden, um auf einem Satz von Werten aus einem Satz von Zeilen zu arbeiten, die als FIRST oder LAST in Bezug auf eine gegebene Sortierspezifikation stehen. Weitere Informationen finden Sie unter FIRST. Sie können Aggregatfunktionen verschachteln. Das folgende Beispiel berechnet den Durchschnitt der maximalen Gehälter aller Abteilungen im Beispielschema hr: Diese Berechnung wertet die innere Aggregate (MAX (Gehalt)) für jede Gruppe aus, die durch die GROUP BY-Klausel (departmentid) und Aggregate definiert wird Die Ergebnisse wieder. Die Aggregatfunktionen sind: Analytische Funktionen Analytische Funktionen berechnen einen Aggregatwert basierend auf einer Gruppe von Zeilen. Sie unterscheiden sich von Aggregatfunktionen darin, dass sie mehrere Zeilen für jede Gruppe zurückgeben. Die Gruppe von Zeilen heißt Fenster und wird durch die analytische Klausel definiert. Für jede Zeile wird ein Schiebefenster von Zeilen definiert. Das Fenster bestimmt den Bereich der Zeilen, die für die Berechnung der aktuellen Zeile verwendet werden. Fenstergrößen können entweder auf eine physikalische Anzahl von Zeilen oder ein logisches Intervall wie z. B. Zeit basieren. Analytische Funktionen sind die letzten Operationen, die in einer Abfrage ausgeführt werden, mit Ausnahme der endgültigen ORDER BY-Klausel. Alle Joins und alle WHERE. GRUPPIERE NACH. Und HAVING-Klauseln abgeschlossen sind, bevor die analytischen Funktionen verarbeitet werden. Daher können analytische Funktionen nur in der Auswahlliste oder ORDER BY-Klausel erscheinen. Analytische Funktionen werden häufig verwendet, um kumulative, bewegte, zentrierte und Berichtsaggregate zu berechnen. PostgreSQL vs. MS SQL Server 0. Was ist das alles über Ich arbeite als Datenanalytiker in einem globalen professionellen Dienstleistungsunternehmen (ein, das Sie sicherlich gehört haben). Ich mache das seit etwa einem Jahrzehnt. Ich habe dieses Jahrzehnt den Umgang mit Daten, Datenbanksoftware, Datenbankhardware, Datenbankbenutzern, Datenbankprogrammierern und Datenanalysemethoden verbracht, so dass ich einiges über diese Dinge weiß. Ich häufig in Kontakt mit Leuten kommen, die sehr wenig über diese Sachen ndash kennen, obwohl einige von ihnen es nicht verwirklichen. Im Laufe der Jahre habe ich die Frage der PostgreSQL vs MS SQL Server viele, viele Male diskutiert. Ein bekanntes Prinzip in der IT sagt: wenn youre es tun, mehr als einmal, automatisieren. Dieses Dokument ist meine Art der Automatisierung dieser Konversation. Wenn nicht anders angegeben, beziehe ich mich auf PostgreSQL 9.3 und MS SQL Server 2014, obwohl meine Erfahrung mit MS SQL Server mit Versionen 2008 R2 und 2012 ndash aus Gründen der Fairness und Relevanz Ich möchte die neueste Version von PostgreSQL auf die neueste vergleichen Version von MS SQL Server. Wo ich habe Ansprüche über MS SQL Server habe ich mein Bestes getan, um zu überprüfen, dass sie auf Version 2014 durch Beratung Microsofts eigene Dokumentation ndash gelten, obwohl aus Gründen, die ich bekommen werde. Ich habe auch weitgehend auf Google, Stack Overflow und die Nutzer des Internets verlassen. Ich weiß, seine nicht wissenschaftlich rigoros, um einen Vergleich wie dies zu tun, wenn ich nicht gleiche Erfahrung mit beiden Datenbanken haben, aber dies ist keine akademische Übung ndash seine ein real-world Vergleich. Ich habe mein ehrliches Bestes getan, um meine Tatsachen über MS SQL-Bedienerrecht ndash zu erhalten, das wir alle wissen, dass es unmöglich ist, den ganzen Internet bullshit zu erhalten. Wenn ich herausfinde, daß Ive etwas falsch erhielt, Kranke es regeln. Ich bin der Vergleich der beiden Datenbanken aus der Sicht eines Datenanalysten. Vielleicht MS SQL Server kickt PostgreSQLs ass als OLTP-Backend (obwohl ich bezweifle es), aber das ist nicht das, was Im hier zu schreiben, weil Im nicht ein OLTP developerDBAsysadmin. Schließlich gibt es eine E-Mail-Adresse oben rechts. Benutzen Sie es bitte, wenn Sie wünschen, dass ich mein Bestes tun werde, um zu reagieren. HAFTUNGSAUSSCHLUSS: Alle subjektiven Meinungen hier sind ausschließlich meine eigenen. 1. Warum PostgreSQL ist, viel besser als MS SQL Server Oops, Spoiler-Alarm. Dieser Abschnitt ist ein Vergleich der beiden Datenbanken hinsichtlich der für die Datenanalyse relevanten Merkmale. 1.1. CSV-Unterstützung CSV ist die De-facto-Standardmethode, um strukturierte (d. h. tabellarische) Daten zu verschieben. Alle RDBMSe können Daten in proprietäre Formate, die nichts anderes lesen können, was für Backups, Replikation und dergleichen gut ist, aber keine Verwendung für die Migration von Daten von System X zu System Y. Eine Datenanalyse-Plattform muss in der Lage sein, zu suchen Bei Daten aus einer Vielzahl von Systemen und produzieren Ergebnisse, die von einer Vielzahl von Systemen gelesen werden können. In der Praxis bedeutet dies, dass es in der Lage sein muss, CSV schnell, zuverlässig, wiederholbar und schmerzlos einnehmen und ausscheiden zu können. Lässt nicht unterschätzen: eine Datenanalyse-Plattform, die nicht CSV robust handhaben kann, ist eine gebrochene, nutzlose Haftung. PostgreSQLs CSV-Unterstützung ist erstklassig. Die COPY TO und COPY FROM Befehle unterstützen die in RFC4180 skizzierte Spezifikation (die dem offiziellen CSV-Standard am nächsten kommt) sowie eine Vielzahl von üblichen und nicht so häufigen Varianten und Dialekten. Diese Befehle sind schnell und robust. Wenn ein Fehler auftritt, geben sie hilfreiche Fehlermeldungen. Wichtig ist, dass sie nicht leise korrumpieren, missverstehen oder verändern. Wenn PostgreSQL sagt, dass Ihr Import funktioniert, dann funktionierte es richtig. Der geringste Hauch von einem Problem und es verlässt den Import und wirft eine hilfreiche Fehlermeldung. (Das klingt vielleicht wählerisch oder unpraktisch, aber es ist tatsächlich ein Beispiel für ein etabliertes Designprinzip: Es ist sinnvoll: würden Sie lieber herausfinden, dass Ihr Import jetzt fehlgeschlagen ist, oder einen Monat ab jetzt, wenn Ihr Kunde sich beschwert, dass Ihre Ergebnisse vorliegen Aus) MS SQL Server kann CSV weder importieren noch exportieren. Die meisten Leute glauben mir nicht, wenn ich ihnen das sage. Dann, an einem gewissen Punkt, sehen sie für sich. In der Regel beobachten sie etwas wie: MS SQL Server stumm schneiden ein Textfeld MS SQL-Server-Text-Encoding-Handling geht falsch MS SQL Server werfen eine Fehlermeldung, weil es nicht verstehen, Zitieren oder Escaping (im Gegensatz zu den gängigen Glauben, Zitieren und Escape sind keine exotischen Erweiterungen CSV. Sie sind grundlegende Konzepte in buchstäblich jede menschenlesbare Daten-Serialisierung Spezifikation. Sie niemandem vertrauen, der nicht weiß, was diese Dinge sind) MS SQL Server exportieren gebrochen, nutzlos CSV Microsofts horrendous Dokumentation. Wie haben sie es geschafft, etwas so einfach wie CSV zu komplizieren Dies ist besonders verwirrend, weil CSV-Parser sind trivial einfach zu schreiben (ich schrieb ein in C und plumpbed es in PHP ein Jahr oder zwei, weil ich nicht glücklich war mit seiner nativen CSV-Handling Das Ganze brachte vielleicht 100 Zeilen Code und drei Stunden ndash, von denen zwei mit SWIG begonnen wurden, was mir damals neu war). Wenn Sie mir nicht glauben, laden Sie diese korrekt formatierte, standardkonforme UTF-8-CSV-Datei herunter und verwenden Sie MS SQL Server, um die durchschnittliche Zeichenfolgenlänge (dh die Anzahl der Zeichen) der letzten Spalte in dieser Datei zu berechnen (sie hat 50 Spalten) . Probieren Sie es aus. (Die Antwort, die Sie suchen, ist genau 183.895.) Natürlich ist die Bestimmung dieses ist trivial einfach in PostgreSQL ndash in der Tat, das zeitaufwändigste Bit ist die Schaffung einer Tabelle mit 50 Spalten, um die Daten zu halten. Schlechtes Verständnis von CSV scheint in Microsoft endemisch zu sein, dass Datei Access und Excel zu brechen. Traurig, aber wahr: einige Datenbank-Programmierer, die ich kenne kürzlich verbrachte viel Zeit und Mühe schriftlich Python-Code, der sanitizes CSV, damit MS SQL Server zu importieren. Sie werent in der Lage, eine Änderung der tatsächlichen Daten in diesem Prozess, though. Dies ist so verrückt wie ein Vermögen auf Photoshop und dann mit einigen benutzerdefinierten Code schreiben, um es zu öffnen, ein JPEG, nur um festzustellen, dass das Bild etwas geändert wurde. 1.2. Ergonomie Jede Datenanalyse-Plattform erwähnenswert ist Turing komplett, was bedeutet, geben oder nehmen, dass jeder von ihnen kann alles, was andere tun können. Es gibt keine solche Sache, wie Sie tun können, X in Software A, aber Sie können nicht tun, X in Software B. Sie können alles tun, in etwas ndash alles, was variiert ist, wie schwer es ist. Gute Werkzeuge machen die Dinge, die Sie brauchen, um leichte schlechte Werkzeuge machen sie schwer. Das ist, was es immer kocht auf. (Das ist alles konzeptionell wahr, wenn nicht buchstäblich wahr - zum Beispiel, keine RDBMS, die ich kenne kann 3D-Grafik zu machen. Aber jeder von ihnen kann jede Berechnungen emulieren, die eine GPU durchführen kann.) PostgreSQL ist eindeutig von Menschen, die tatsächlich kümmern geschrieben Dinge erledigt bekommen . MS SQL Server fühlt sich an, wie es von Leuten geschrieben wurde, die nie wirklich MS SQL Server verwenden müssen, um alles zu erreichen. Hier einige Beispiele: PostgreSQL unterstützt DROP TABLE IF EXISTS. Die die intelligente und offensichtliche Weise des Sagens ist, wenn diese Tabelle nicht existiert, nichts tun, aber wenn es tut, es loswerden. So etwas wie dieses: Heres, wie Sie es in MS SQL Server tun müssen: Ja, seine nur eine zusätzliche Zeile Code, aber beachten Sie den mysteriösen zweiten Parameter, um die OBJECTID-Funktion. Sie müssen das mit NV ersetzen, um eine Ansicht zu löschen. Sein NP für eine gespeicherte Prozedur. Ich habe nicht gelernt, die verschiedenen Buchstaben für alle verschiedenen Arten von Datenbank-Objekten (warum sollte ich) Beachten Sie auch, dass der Tabellenname unnötig wiederholt wird. Wenn Ihre Konzentration rutscht für einen Moment, seine tote leicht, dies zu tun: Siehe was ist dort passiert Dies ist eine zuverlässige Quelle für lästige, zeitraubende Fehler. PostgreSQL unterstützt den DROP SCHEMA CASCADE. Die ein Schema und alle Datenbankobjekte in ihm sinkt. Dies ist sehr, sehr wichtig für eine robuste Analytics Delivery Methodologie, wo Tear-down-and-Rebuild ist das zugrunde liegende Prinzip der wiederholbaren, auditiven, kooperativen Analyse-Arbeit. Es gibt keine solche Einrichtung in MS SQL Server. Sie müssen alle Objekte im Schema manuell und in der richtigen Reihenfolge ablegen. Denn wenn Sie versuchen, ein Objekt zu löschen, auf dem ein anderes Objekt abhängt, löst MS SQL Server einfach einen Fehler aus. Dies gibt eine Vorstellung davon, wie mühsam dieser Prozess sein kann. PostgreSQL unterstützt CREATE TABLE AS. Ein kleines Beispiel: Dies bedeutet, dass Sie alles, aber die erste Zeile markieren und ausführen können, was eine nützliche und gemeinsame Aufgabe bei der Entwicklung von SQL-Code ist. In MS SQL Server geht die Tabellenerstellung wie folgt aus: Um die einfache SELECT-Anweisung auszuführen, müssen Sie das INTO-Bit auskommentieren oder entfernen. Ja, kommentieren zwei Zeilen ist einfach, das ist nicht der Punkt. Der Punkt ist, dass in PostgreSQL können Sie diese einfache Aufgabe ohne Änderung des Codes und in MS SQL Server Sie cant, und das führt zu einer weiteren potenziellen Quelle von Bugs und Ärgernisse. In PostgreSQL können Sie so viele SQL-Anweisungen ausführen, wie Sie in einem Batch mögen, solange Sie jede Anweisung mit einem Semikolon beendet haben, können Sie ausführen, was Kombination von Anweisungen, die Sie mögen. Für die Ausführung von automatisierten Batch-Prozessen oder reproduzierbaren Datenaufbauten oder Ausgabeaufgaben ist dies eine wesentliche Funktionalität. In MS SQL Server kann eine CREATE PROCEDURE-Anweisung nicht halb durch einen Batch von SQL-Anweisungen angezeigt werden. Theres kein guter Grund dafür, seine nur eine willkürliche Einschränkung. Es bedeutet, dass zusätzliche manuelle Schritte oft erforderlich sind, um eine große Batch von SQL auszuführen. Manuelle Schritte erhöhen das Risiko und senken die Effizienz. PostgreSQL unterstützt die RETURNING-Klausel, die UPDATE ermöglicht. INSERT - und DELETE-Anweisungen, um Werte aus den betroffenen Zeilen zurückzugeben. Dies ist elegant und nützlich. MS SQL Server hat die OUTPUT-Klausel, die eine separate Tabellenvariablendefinition benötigt, um zu funktionieren. Dies ist klobig und unpraktisch und zwingt einen Programmierer, unnötigen Boilerplate-Code zu erzeugen und zu warten. PostgreSQL unterstützt String-Zitate wie folgt: Dies ist äußerst nützlich für die Generierung von dynamischem SQL, weil (a) es dem Benutzer erlaubt, mühsames und unzuverlässiges manuelles Zitieren und Escaping zu vermeiden, wenn Literal-Strings verschachtelt sind, und (b) seit Texteditoren und IDEs dazu neigen Erkennung als String-Trennzeichen, Syntax-Hervorhebung bleibt auch in dynamischen SQL-Code funktional. PostgreSQL ermöglicht es Ihnen, Verfahrenssprachen einfach durch das Einreichen von Code in die Datenbank-Engine schreiben Sie Verfahrenscode in Python oder Perl oder R oder JavaScript oder eine der anderen unterstützten Sprachen (siehe unten) direkt neben Ihrem SQL, in demselben Skript. Dies ist bequem, schnell, wartbar, leicht zu überprüfen, einfach wiederzuverwenden und so weiter. In MS SQL Server können Sie entweder die lumpy, langsame, umständliche T-SQL-Verfahrenssprache verwenden oder Sie können eine. NET-Sprache verwenden, um eine Assembly zu erstellen und in die Datenbank zu laden. Dies bedeutet, dass Ihr Code an zwei verschiedenen Orten ist und Sie müssen eine Reihe von GUI-basierten manuellen Schritten durchlaufen, um es zu ändern. Es macht die Verpackung bis alle Ihre Sachen an einem Ort schwerer und fehleranfälliger. Und es gibt viele weitere Beispiele gibt. Jedes dieser Dinge, isoliert, kann als ein relativ geringfügiges niggle erscheinen, aber der Gesamteffekt ist, dass immer echte Arbeit in MS SQL Server ausgeführt wird wesentlich schwerer und fehleranfälliger als in PostgreSQL, und Datenanalysten verbringen wertvolle Zeit und Energie Auf Workarounds und manuelle Prozesse, anstatt sich auf das eigentliche Problem zu konzentrieren. Update: es wurde mir gezeigt, dass eine wirklich nützliche Funktion MS SQL Server hat, die PostgreSQL fehlt ist die Fähigkeit, Variablen in SQL-Skripten deklarieren. So: PostgreSQL kann dies nicht tun. Ich wünschte, es könnte, denn es gibt eine Menge von Anwendungen für eine solche Funktion. 1.3. Sie können PostgreSQL in Linux, BSD etc. laufen lassen (und natürlich Windows) Wer die Entwicklungen in der IT verfolgt, weiß, dass Cross-Plattform eine Sache ist. Cross-Plattform-Unterstützung ist wohl die Killer-Funktion von Java, die eigentlich eine etwas holprige, hässliche Programmiersprache, aber dennoch enorm erfolgreich, einflussreich und weit verbreitet. Microsoft hat nicht mehr das Monopol es einmal genossen auf dem Desktop, dank der Aufstieg von Linux und Apple. IT-Infrastrukturen werden zunehmend heterogen durch die Flexibilität von Cloud-Services und einfachen Zugang zu leistungsstarker Virtualisierungstechnologie. Cross-Plattform-Software ist über die Benutzer die Kontrolle über ihre Infrastruktur. (Bei der Arbeit verwalte ich derzeit mehrere PostgreSQL-Datenbanken, einige in Windows und einige in Ubuntu Linux. I und meine Kollegen frei verschieben Code und Datenbank-Dumps zwischen ihnen. Wir verwenden Python und PHP, weil sie auch in beiden Betriebssystemen arbeiten. Es funktioniert alles nur .) Microsofts Politik ist und war immer Verkäufer-Lock-in. Sie dont open-Source ihren Code sie nicht bieten Cross-Plattform-Versionen ihrer Software, die sie sogar ein ganzes Ökosystem erfunden. NET, entworfen, um eine harte Linie zwischen Microsoft-Benutzern und Nicht-Microsoft-Benutzern zu zeichnen. Das ist gut für sie, weil sie ihre Einnahmen sichert. Es ist schlecht für Sie, der Benutzer, weil es Ihre Entscheidungen beschränkt und schafft unnötige Arbeit für Sie. (Update: ein paar Tage, nachdem ich dieses veröffentlichte, Microsoft machte mich aussehen wie ein Prat mit der Ankündigung, dass es Open-Sourcing. NET. Dies ist ein großer Schritt, aber nicht knacken öffnen Sie die Bollinger nur noch.) Nun, das ist Nicht ein Linux vs Windows-Dokument, obwohl Im sicher Ill am Ende schriftlich eines dieser an einem gewissen Punkt. Es genügt zu sagen, dass für die reale IT-Arbeit Linux (und die UNIX-ähnliche Familie: Solaris, BSD etc.) Windows im Staub verlässt. UNIX-ähnliche Betriebssysteme dominieren den Server-Markt, Cloud-Services, Supercomputing (in diesem Bereich ist es ein nahezu Monopol) und technisches Computing, und mit gutem Grund ndash diese Systeme werden von Techies für techies entworfen. Dadurch handeln sie für enorme Kraft und Flexibilität. Ein richtiges UNIX-ähnliches Betriebssystem ist nicht nur eine nette Befehlszeile ndash es ist ein Ökosystem von Programmen, Dienstprogrammen, Funktionalität und Unterstützung, die echte Arbeit macht effizient und angenehm macht. Ein kompetenter Linux-Hacker kann in einer einzigen Wegwerflinie des Bash-Skripts eine Aufgabe schaffen, die in Windows schwierig und zeitraubend wäre. (Beispiel: Neulich suchte ich eine Freundesfilmsammlung und er meinte, die Gesamtzahl der Dateien im Dateisystem sei hoch, wenn man bedenkt, wie viele Filme er hatte, und er fragte sich, ob er vielleicht versehentlich einen großen Ordner kopiert hatte Ich habe eine rekursive Anzahl von Dateien-pro-Ordner für ihn wie folgt: Das Ganze dauerte etwa eine Minute zu schreiben und eine Sekunde zu laufen. Es bestätigte, dass einige seiner Ordner hatte ein Problem und Sagte, was sie waren, wie würden Sie dies in Windows tun) Für die Datenanalyse, ein RDBMS existiert nicht in einem Vakuum ist es Teil eines Tool-Stack. Deshalb ist die Umwelt wichtig. MS SQL Server ist auf Windows beschränkt, und Windows ist einfach eine schlechte Analyseumgebung. 1.4. Procedural Language Features Dies ist ein Biggie. Pure deklarative SQL ist gut, was es für ndash relationalen Daten Manipulation und Abfrage entworfen wurde. Sie erreichen schnell ihre Grenzen, wenn Sie versuchen, sie für komplexere analytische Prozesse wie komplexe Zinsrechnungen, Zeitreihenanalyse und allgemeines Algorithmusdesign zu nutzen. SQL-Datenbank-Anbieter wissen dies, so dass fast alle SQL-Datenbanken eine Art von Verfahrenssprache zu implementieren. Dies ermöglicht es einem Datenbankbenutzer, imperativ-artigen Code für komplexere oder fiddly Aufgaben zu schreiben. PostgreSQLs Verfahrenssprache Unterstützung ist außergewöhnlich. Sein unmöglich, ihm in einem kurzen Raum gerecht zu werden, aber heres eine Probe der Waren. Jede dieser Verfahrenssprachen kann zum Schreiben gespeicherter Prozeduren und Funktionen verwendet werden oder einfach in einen Codeblock, der inline ausgeführt werden soll, abgelegt werden. PLPGSQL: Dies ist PostgreSQLs native Verfahrenssprache. Es ist wie Oracles PLSQL, aber moderner und feature-complete. PLV8: Die V8-JavaScript-Engine von Google Chrome ist in PostgreSQL verfügbar. Diese Engine ist stabil, Feature-packed und absurd schnell ndash oft nähert sich der Ausführungsgeschwindigkeit der kompiliert, optimiert C. Kombinieren Sie das mit PostgreSQLs native Unterstützung für die JSON-Datentyp (siehe unten) und Sie haben ultimative Macht und Flexibilität in einem einzigen Paket. Noch besser ist es, dass PLV8 den globalen (d. H. Crossfunktionsaufruf) - Status unterstützt, so dass der Benutzer selektiv Daten im RAM für schnellen wahlfreien Zugriff zwischenspeichern kann. Angenommen, Sie müssen 100.000 Zeilen von Daten aus Tabelle A auf jeweils 1.000.000 Zeilen von Daten aus Tabelle B verwenden. In traditionellen SQL müssen Sie entweder diese Tabellen beitreten (was zu einer 100bn Zeile Zwischen-Tabelle, die alle aber die meisten töten wird Immense Server) oder etwas Ähnliches wie eine skalare Unterabfrage (oder schlimmer, Cursor-basierte verschachtelte Schleifen), was zu lähmenden IO-Last, wenn der Abfrageplaner nicht Ihre Intentionen richtig liest. In PLV8 legen Sie einfach die Tabelle A im Speicher ab und führen eine Funktion für jede Zeile der Tabelle B ndash aus, die Ihnen einen RAM-Qualitätszugriff (vernachlässigbare Latenzzeit und Direktzugriffsstrafe keine nichtflüchtige IO-Last) an die 100k-Zeilentabelle verleiht . Ich tat dies auf eine echte Arbeit vor kurzem ndash mein PostgreSQLPLV8-Code war etwa 80-mal schneller als die MS-T-SQL-Lösung und der Code war viel kleiner und wartbar. Da es etwa 23 Sekunden dauerte, anstatt eine halbe Stunde zu laufen, konnte ich 20 Run-Test-Modifikationszyklen in einer Stunde ausführen, was zu funktionsübergreifendem, richtig getestetem und fehlerfreiem Code führte. Schauen Sie hier für mehr Details auf diesem. (Alle diese Run-Test-Modifikationszyklen waren nur möglich, weil DROP SCHEMA CASCADE und die Freiheit, CREATE FUNCTION-Anweisungen in der Mitte einer Anweisung Batch auszuführen, wie oben erläutert.) PLPython: Sie können voll verwenden Python in PostgreSQL. Python2 oder Python 3, nehmen Sie Ihre Auswahl, und ja, erhalten Sie das enorme Ökosystem der Bibliotheken, für die Python ist rechtmäßig berühmt. Lust auf das Ausführen eines SVM von scikit-learn oder eine beliebige Genauigkeit Arithmetik von gmpy2 in der Mitte einer SQL-Abfrage Kein Problem PLPerl: Perl hat sich aus der Mode seit einiger Zeit, aber seine Vielseitigkeit verdient es einen Ruf als die Schweizer Armee Messer der Programmiersprachen. In PostgreSQL haben Sie voll Perl als Verfahrenssprache. PLR: R ist die de facto standardisierte statistische Programmierumgebung in Wissenschaft und Datenwissenschaft und mit gutem Grund - sie ist kostenlos, robust, voll funktionsfähig und unterstützt durch eine enorme Bibliothek von hochwertigen Plugins und Add-Ons. PostgreSQL ermöglicht es Ihnen, R als Verfahrenssprache zu verwenden. Java, Lua, sh, Tcl, Ruby und PHP werden auch als Verfahrenssprachen in PostgreSQL unterstützt. C: gehört nicht ganz in diese Liste, weil Sie es separat kompilieren müssen, aber es ist eine Erwähnung wert. In PostgreSQL ist es sehr einfach, Funktionen zu erstellen, die kompilierte, optimierte C (oder C oder Assembler) im Datenbank-Backend ausführen. Dies ist eine Power-User-Funktion, die konkurrenzlose Geschwindigkeit und feine Steuerung der Speicherverwaltung und Ressourcennutzung für Aufgaben bietet, bei denen die Leistung kritisch ist. Ich habe dies verwendet, um eine komplexe, stateful Zahlungsverarbeitung Algorithmus auf einer Million Zeilen von Daten pro Sekunde ndash und das war auf einem Desktop-PC zu implementieren. MS SQL Servers eingebaute Verfahrenssprache (Teil ihrer T-SQL-Erweiterung zu SQL) ist klobig, langsam und Feature-arm. Es ist auch anfällig für subtile Fehler und Bugs, wie Microsofts eigene Dokumentation manchmal anerkennt. Ich habe noch nie einen Datenbank-Benutzer, der die T-SQL-Verfahrenssprache mag getroffen. Was ist mit der Tatsache, dass Sie Assemblys machen können in. NET-Sprachen und verwenden Sie sie dann in MS SQL Server Dies zählt nicht als prozedurale Sprache zu unterstützen, weil Sie nicht senden können diesen Code an die Datenbank-Engine direkt. Manageability und Ergonomie sind von entscheidender Bedeutung. Das Einfügen von Python-Code inline in Ihre Datenbankabfrage ist einfach und bequem, Visual Studio zu starten, Projekte zu verwalten und DLL-Dateien herumzuwerfen (alle in GUI-basierten Prozessen, die nicht korrekt skriptgesteuert, versionskontrolliert, automatisiert oder überprüft werden können) ist umständlich, Fehler Und nicht skalierbar. In jedem Fall ist dieser Mechanismus auf. NET-Sprachen beschränkt. 1.5. Native reguläre Ausdrucksunterstützung Reguläre Ausdrücke (Regexen oder Regexe) sind für die analytische Arbeit als arithmetisches ndash grundlegend, sie sind die erste Wahl (und oft nur Auswahl) für eine Vielzahl von Textverarbeitungsaufgaben. Ein Datenanalyse-Tool ohne Regex-Unterstützung ist wie ein Fahrrad ohne Sattel ndash Sie noch verwenden können, aber es ist schmerzhaft. PostgreSQL hat zertrümmerte Out-of-the-Box-Unterstützung für regex. Einige Beispiele: Alle Zeilen beginnen mit einer wiederholten Zahl, gefolgt von einem Vokal: Holen Sie sich den ersten isolierten Hex-String, der in einem Feld vorkommt: Brechen Sie einen String auf Whitespace und geben Sie jedes Fragment in einer separaten Zeile zurück: Case-insensitive Suche alle Wörter in einem String Mit mindestens 10 Buchstaben: MS SQL Server hat LIKE. SUBSTRING. PATINDEX und so weiter, die nicht mit der richtigen Regex-Unterstützung vergleichbar sind (wenn Sie daran zweifeln, versuchen Sie es mit den oben genannten Beispielen). Es gibt Drittanbieter-Regex-Bibliotheken für MS SQL Server theyre nur nicht so gut wie PostgreSQLs unterstützen, und die Notwendigkeit, zu erhalten und installieren sie separat fügt Admin-Overhead. Beachten Sie auch, dass PostgreSQLs umfangreiche Verfahrenssprachenunterstützung Ihnen auch einige andere regex Maschinen und ihre verschiedenen Eigenschaften - z. B. Pythons Regex-Bibliothek bietet die zusätzliche Macht der positiven und negativen Lookbehind Behauptungen. Dies steht im Einklang mit dem allgemeinen Thema der PostgreSQL gibt Ihnen alle Werkzeuge, die Sie brauchen, um tatsächlich Dinge getan. 1.6. Benutzerdefinierte Aggregatfunktionen Dies ist ein Feature, das technisch sowohl von PostgreSQL als auch von MS SQL Server angeboten wird. Die Implementierungen unterscheiden sich jedoch sehr. In PostgreSQL, sind benutzerdefinierte Aggregate bequem und einfach zu bedienen, was in schnelle Problemlösung und wartbaren Code: Elegant, eh Ein benutzerdefiniertes Aggregat wird in Form eines internen Zustandes und eine Möglichkeit, diesen Zustand zu ändern, wenn wir neue Werte in die Aggregatfunktion. In diesem Fall starten wir jeden Kunden mit Null-Balance und keine Zinsen aufgelaufen, und an jedem Tag fangen wir Zinsen angemessen und Rechnung für Zahlungen und Abhebungen. Wir verbinden die Zinsen am 1. eines jeden Monats. Beachten Sie, dass das Aggregat eine ORDER BY-Klausel akzeptiert (da im Gegensatz zu SUM MAX und MIN dieses Aggregat auftragsabhängig ist) und PostgreSQL Operatoren zum Extrahieren von Werten aus JSON-Objekten bereitstellt. So, in 28 Zeilen von Code weve erstellt den Rahmen für monatliche Compoundierung Zinsen auf Bankkonten und verwendet es, um endgültige Salden zu berechnen. Wenn der Methodik Merkmale hinzugefügt werden sollen (z. B. Zinsänderungen in Abhängigkeit von debitcredit-Saldo, Erkennung von außergewöhnlichen Umständen), ist dies in der Übergangsfunktion genau richtig und wird in einer geeigneten Sprache für die Implementierung einer komplexen Logik geschrieben. (Tragische Seite beachten: Ich habe gesehen, große Organisationen verbringen Zehntausende von Pfund über Wochen der Arbeit versucht, die gleiche Sache mit ärmeren Tools zu erreichen.) MS SQL Server, auf der anderen Seite macht es absurd schwierig. Im Übrigen sind die Beispiele in der zweiten Verbindung für die Implementierung eines einfachen String-Verkettungsaggregats. Beachten Sie die riesige Menge an Code und Gymnastik erforderlich, um diese einfache Funktion implementieren (die PostgreSQL bietet out of the box, übrigens. Wahrscheinlich, weil seine nützlich). MS SQL Server erlaubt auch keine Reihenfolge in der Aggregat angegeben werden, die diese Funktion nutzlos für meine Art von Arbeit ndash mit MS SQL Server macht, ist die Reihenfolge der Zeichenfolge Verknüpfung zufällig, so dass die Ergebnisse einer Abfrage mit dieser Funktion sind Nicht deterministisch (sie können sich ändern von run to run) und der Code wird nicht eine Qualitätsprüfung bestehen. Der Mangel an Bestellung Unterstützung bricht auch Code wie das Zinsrechnungsbeispiel oben. Soweit ich sagen kann, können Sie dies nur mit einem benutzerdefinierten MS SQL Server-Aggregat tun. (Es ist tatsächlich möglich, dass MS SQL Server eine deterministische String-Verkettung Aggregation in reinen SQL, aber Sie müssen die RECURSIVE Abfrage-Funktionalität zu tun, es zu tun. Obwohl eine interessante akademische Übung, führt dies zu langsamen, unlesbaren, unmaintainable Code und ist nicht Eine realistische Lösung). 1.7. Unicode-Unterstützung Lange vorbei sind die Zeiten, in denen ASCII universell war, Charakter und Byte waren fungible Begriffe und ausländische (aus anglozentrischer Sicht) Text war eine exotische Ausnahme. Eine korrekte internationale Sprachunterstützung ist nicht mehr optional. Die Lösung für all dies ist Unicode. Es gibt viele Missverständnisse über Unicode da draußen. Sein nicht ein Zeichensatz, sein nicht eine Codepage, sein nicht ein Dateiformat und sein nichts, was auch immer mit Verschlüsselung zu tun hat. Eine Erforschung, wie Unicode arbeitet ist faszinierend, aber über den Rahmen dieses Dokuments ndash Ich empfehle herzlich Googeln es und arbeitet durch ein paar Beispiele. Die wichtigsten Punkte für Unicode, die für die Datenbankfunktionalität relevant sind, sind: Unicode-codierter Text (für unsere Zwecke bedeutet dies entweder UTF-8 oder UTF-16) ist eine Codierung mit variabler Breite. In UTF-8 kann ein Zeichen ein, zwei, drei oder vier Bytes darstellen. In UTF-16 seine entweder zwei oder vier. Dies bedeutet, dass Operationen wie das Aufnehmen von Teilzeichenfolgen und das Messen von Zeichenkettenlängen Unicode-bewusst sein müssen, um ordnungsgemäß zu funktionieren. Nicht alle Bytes sind gültig Unicode. Manipulieren gültigen Unicode ohne zu wissen, seine Unicode wird wahrscheinlich zu produzieren, was nicht gültig Unicode. UTF-8 und UTF-16 sind nicht kompatibel. Wenn Sie eine Datei von jedem Typ zu nehmen und verkettet, Sie (wahrscheinlich) am Ende mit einer Datei, die weder gültige UTF-8 noch gültige UTF-16. Für Text, der meist in ASCII passt, ist UTF-8 etwa doppelt so platzsparend wie UTF-16. PostgreSQL unterstützt UTF-8. Seine CHAR. VARCHAR - und TEXT-Typen sind standardmäßig UTF-8, was bedeutet, dass sie nur UTF-8-Daten akzeptieren und alle von ihnen angewandten Transformationen von Stringverkettung und Suche nach regulären Ausdrücken UTF-8-bewusst sind. Alles funktioniert. MS SQL Server 2008 unterstützt nicht UTF-16 es unterstützt UCS-2, eine veraltete Untermenge von UTF-16. Was dies bedeutet, ist, dass die meiste Zeit, wird es aussehen, wie seine Arbeit gut, und gelegentlich wird es stillschweigend Ihre Daten beschädigen. Da es Text als Zeichenfolge von breiten (d. h. 2 Byte) Zeichen interpretiert, schneidet es glücklicherweise ein 4-Byte-UTF-16-Zeichen in der Hälfte. Am besten, dies führt zu beschädigten Daten. Schlimmstenfalls wird etwas anderes in Ihrem toolchain brechen schlecht und youll haben eine Katastrophe auf Ihren Händen. Apologen für MS sind schnell darauf hinzuweisen, dass dies unwahrscheinlich ist, weil es die Daten benötigen, um etwas außerhalb Unicodes grundlegende mehrsprachige Flugzeug enthalten. Das ist völlig fehlt der Punkt. Eine einzige Datenbank dient zum Speichern, Zurückholen und Manipulieren von Daten. Eine Datenbank, die gebrochen werden kann, indem Sie die falschen Daten in sie ist so nutzlos wie ein Router, der bricht, wenn Sie die falsche Datei herunterladen. MS SQL Server-Versionen seit 2012 haben UTF-16 richtig unterstützt, wenn Sie sicherstellen, dass Sie eine UTF-16-kompatible Sortierung für Ihre Datenbank auswählen. Es ist verblüffend, dass dies (a) fakultativ ist und (b) bis 2012 implementiert. Besser spät als nie, nehme ich an. 1.8. Datentypen, die ordnungsgemäß funktionieren Ein allgemeines Missverständnis ist, dass alle Datenbanken die gleichen Typen ndash INT haben. VERKOHLEN. DATE und so weiter. Das ist nicht wahr. PostgreSQLs Typ-System ist wirklich nützlich und intuitiv, frei von Ärgernissen, die Bugs oder langsame Arbeit nach unten und, wie üblich, scheinbar mit Produktivität im Auge entworfen. MS SQL-Server-Typ-System, durch Vergleich, fühlt sich wie Beta-Software. Es cant Touch der Feature-Set von PostgreSQLs-Typ-System und es ist mit Fallen warten, um den unerwünschten Benutzer zu versorgen. Werfen wir einen Blick: CHAR, VARCHAR und Familie PostgreSQL: Die Docs ermutigen Sie aktiv, einfach den TEXT-Typ zu verwenden. Dies ist ein leistungsfähiger, UTF-8-validierte Textspeichertyp, der Strings bis zu 1 GB Größe speichert. Es unterstützt alle Text-Operationen PostgreSQL ist in der Lage: einfache Verkettung und Substringing Regex-Suche, Matching und Splitting Volltext-Suche Casting-Transformation und so weiter. Wenn Sie Textdaten haben, kleben Sie es in ein TEXT-Feld und weitermachen. Da alles in einem TEXT-Feld (oder in diesem Fall CHAR - oder VARCHAR-Felder) UTF-8 sein muss, gibt es kein Problem mit Encodierungs-Inkompatibilität. Da UTF-8 die de facto universelle Textcodierung ist, ist die Konvertierung von Text einfach und zuverlässig. Da UTF-8 eine Obermenge von ASCII ist, ist diese Umwandlung oft trivial einfach oder gänzlich unnötig. Alles funktioniert. MS SQL Server: es ist eine ziemlich traurige Geschichte. Die TEXT - und NTEXT-Typen bestehen und erstrecken sich auf 2GB. Bafflingly, aber, dont Unterstützung Casting. Auch, verwenden Sie sie nicht, sagt MS ndash werden sie in einer zukünftigen Version von MS SQL Server entfernt werden. Sie sollten CHAR verwenden. VARCHAR und ihre N - prefixed Versionen statt. Leider hat VARCHAR (MAX) schlechte Leistungsmerkmale und VARCHAR (8000) (die nächste größte Größe, aus irgendeinem Grund) Tops bei 8.000 Bytes. (Die 4.000 Zeichen für NVARCHAR.) Denken Sie daran, wie PostgreSQLs Beharren auf einer einzigen Text-Kodierung pro Datenbank macht alles reibungslos Nicht so in MS-Land: Wie bei früheren Versionen von SQL Server, wird Datenverlust während der Codepage-Übersetzungen nicht gemeldet. Link Mit anderen Worten, MS SQL Server könnte Ihre Daten beschädigen, und Sie wissen es nicht, bis etwas anderes schief geht. Das ist ganz einfach ein Dealbreaker. Eine Datenanalyseplattform, die Ihre Daten stumm ändern, verfälschen oder verlieren könnte, ist eine enorme Haftung. Betrachten Sie die Absurdität des Forking-out für einen Server mit teuren ECC RAM als Verteidigung gegen Daten-Korruption durch kosmische Strahlen verursacht, und dann mit Software auf sie, die Ihre Daten sowieso korrumpieren könnte. Datums - und Uhrzeitarten PostgreSQL: Sie erhalten DATE. ZEIT. TIMESTAMP und TIMESTAMP MIT ZEITZONE. Die alle genau das tun, was man erwarten würde. Sie haben auch fantastische Reichweite und Präzision, unterstützt Mikrosekunde Auflösung von der 5. Jahrtausend v. Chr. Bis fast 300 Jahrtausende in der Zukunft. Sie nehmen Eingang in einer Vielzahl von Formaten und die letzte hat volle Unterstützung für Zeitzonen. Sie können zu und von Unix-Zeit konvertiert werden, was für die Interoperabilität mit anderen Systemen sehr wichtig ist. Sie können die speziellen Werte infinity und - infinity. Das ist keine metaphysisch-theologisch-philosophische Aussage, sondern eine sehr nützliche semantische Konstruktion. Stellen Sie zum Beispiel ein Benutzer-Kennwort-Ablaufdatum auf unendlich ein, um anzugeben, dass es sein Kennwort nicht ändern muss. Die normale Weise, dies zu tun ist, NULL oder irgendein Datum weit in der Zukunft zu verwenden, aber diese sind ungeschickt Hacks ndash sie beide beinhalten, setzen ungenaue Informationen in der Datenbank und Schreiben Anwendungslogik zu kompensieren. Was passiert, wenn ein Entwickler NULL oder 3499-12-31 sieht. If youre lucky, he knows the secret handshakes and isnt confused by it. If not, he assumes either that the date is unknown or that it really does refer to the 4th millennium, and you have a problem. The cumulative effect of hacks, workarounds and kludges like this is unreliable systems, unhappy programmers and increased business risk. Helpful semantics like infinity and - infinity allow you to say what you mean and write consistent, readable application logic. They also support the INTERVAL type, which is so useful it has its own section right after this one. Casting and conversion of date and time types is easy and intuitive - you can cast any type to TEXT. and the tochar and totimestamp functions give you ultimate flexibility, allowing conversion in both directions using format strings. For example: and, going in the other direction, As usual, it just works. As a data analyst, I care very much about a databases date-handling ability, because dates and times tend to occur in a multitude of different formats and they are usually critical to the analysis itself. MS SQL Server: dates can only have positive 4-digit years, so they are restricted to 0001 AD to 9999 AD. They do not support infinity and - infinity. They do not support interval types, so date arithmetic is tedious and clunky. You can convert them to and from UNIX time, but its a hack involving adding seconds to the UNIX epoch, 1970-01-01T00:00:00Z, which you therefore have to know and be willing to hardcode into your application. Date conversion deserves a special mention, because even by MS SQL Servers shoddy standards its bloody awful. The CONVERT function takes the place of PostgreSQLs tochar and totimestamp. but it works like this: Thats right ndash youre simply expected to know that 126 is the code for converting strings in that format to a datetime. MSDN provides a table of these magic numbers. I didnt give the same example as for PostgreSQL because I couldnt find a magic number corresponding to the right format for Saturday 03 Feb 2001. If someone gave you data with such dates in it, I guess youd have to do some string manipulation (pity the string manipulation facilities in MS SQL Server are almost non-existent. ) PostgreSQL: the INTERVAL type represents a period of time, such as 30 microseconds or 50 years. It can also be negative, which may seem counterintuitive until you remember that the word ago exists. PostgreSQL also knows about ago, in fact, and will accept strings like 1 day ago as interval values (this will be internally represented as an interval of -1 days). Interval values let you do intuitive date arithmetic and store time durations as first-class data values. They work exactly as you expect and can be freely casted and converted to and from anything which makes sense. MS SQL Server: no support for interval types. PostgreSQL: arrays are supported as a first-class data type, meaning fields in tables, variables in PLPGSQL, parameters to functions and so on can be arrays. Arrays can contain any data type you like, including other arrays. This is very, very useful . Here are some of the things you can do with arrays: Store the results of function calls with arbitrarily-many return values, such as regex matches Represent a string as integer word IDs, for use in fast text matching algorithms Aggregation of multiple data values across groups, for efficient cross-tabulation Perform row operations using multiple data values without the expense of a join Accurately and semantically represent array data from other applications in your tool stack Feed array data to other applications in your tool stack I cant think of any programming languages which dont support arrays, other than crazy ones like Brainfuck and Malbolge. Arrays are so useful that they are ubiquitous. Any system, especially a data analytics platform, which doesnt support them is crippled. MS SQL Server: no support for arrays. PostgreSQL: full support for JSON, including a large set of utility functions for transforming between JSON types and tables (in both directions), retreiving values from JSON data and constructing JSON data. Parsing and stringification are handled by simple casts, which as a rule in PostgreSQL are intelligent and robust. The PLV8 procedural language works as seamlessly as you would expect with JSON ndash in fact, a JSON-type internal state in a custom aggregate (see this example) whose transition function is written in PLV8 provides a declarativeimperative best-of-both-worlds so powerful and convenient it feels like cheating. JSON (and its variants, such as JSONB) is of course the de facto standard data transfer format on the web and in several other data platforms, such as MongoDB and ElasticSearch, and in fact any system with a RESTful interface. Aspiring Analytics-as-a-Service providers take note. MS SQL Server: no support for JSON. PostgreSQL: HSTORE is a PostgreSQL extension which implements a fast key-value store as a data type. Like arrays, this is very useful because virtually every high-level programming language has such a concept (and virtually every programming language has such a concept because it is very useful). JavaScript has objects, PHP has associative arrays, Python has dicts, C has std::map and std::unorderedmap. Go has maps. And so on. In fact, the notion of a key-value store is so important and useful that there exists a whole class of NoSQL databases which use it as their main storage paradigm. Theyre called, uh, key-value stores . There are also some fun unexpected uses of such a data type. A colleague recently asked me if there was a good way to deduplicate a text array. Heres what I came up with: i. e. put the array into both the keys and values of an HSTORE, forcing a dedupe to take place (since key values are unique) then retrieve the keys from the HSTORE. Theres that PostgreSQL versatility again. MS SQL Server: No support for key-value storage. Range types PostgreSQL: range types represent, well, ranges. Every database programmer has seen fields called startdate and enddate. and most of them have had to implement logic to detect overlaps. Some have even found, the hard way, that joins to ranges using BETWEEN can go horribly wrong, for a number of reasons. PostgreSQLs approach is to treat time ranges as first-class data types. Not only can you put a range of time (or INT s or NUMERIC s or whatever) into a single data value, you can use a host of built-in operators to manipulate and query ranges safely and quickly. You can even apply specially-developed indices to them to massively accelerate queries that use these operators. In short, PostgreSQL treats ranges with the importance they deserve and gives you the tools to work with them effectively. Im trying not to make this document a mere list of links to the PostgreSQL docs, but just this once, I suggest you go and see for yourself . (Oh, and if the pre-defined types dont meet your needs, you can define your own ones. You dont have to touch the source code, the database exposes methods to allow you to do this.) MS SQL Server: no support for range types. NUMERIC and DECIMAL PostgreSQL: NUMERIC (and DECIMAL - theyre symonyms) is near-as-dammit arbitrary precision: it supports 131,072 digits before the decimal point and 16,383 digits after the decimal point. If youre running a bank, doing technical computation, landing spaceships on comets or simply doing something where you cannot tolerate rounding errors, youre covered. MS SQL Server: NUMERIC (and DECIMAL - theyre symonyms) supports a maximum of 38 decimal places of precision in total. PostgreSQL: XML is supported as a data type and the database offers a variety of functions for working with XML. Xpath querying is supported. MS SQL Server: finally, some good news MS SQL Server has an XML data type too, and offers plenty of support for working with it. (Shame XML is going out of style. ) 1.9. Scriptability PostgreSQL can be driven entirely from the command line, and since it works in operating systems with proper command lines (i. e. everything except Windows), this is highly effective and secure. You can SSH to a server and configure PostgreSQL from your mobile phone, if you have to (I have done so more than once). You can automate deployment, performance-tuning, security, admin and analytics tasks with scripts. Scripts are very important because unlike GUI processes, they can be copied, version-controlled, documented, automated, reviewed, batched and diffed. For serious work, text editors and command lines are king. MS SQL Server is driven through a GUI. I dont know to what extent it can be automated with Powershell I do know that if you Google for help and advice on getting things done in MS SQL Server, you get a lot of people saying right-click on your database, then click on Tasks. . GUIs do not work well across low-bandwidth or high-latency connections text-based shells do. As I write I am preparing to do some sysadmin on a server 3,500 miles away, on a VPN via a shaky WiFi hotspot, and thanking my lucky stars its an UbuntuPostgreSQL box. (Who on Earth wants a GUI on a server anyway) 1.10. Good external language bindings PostgreSQL is very, very easy to connect to and use from programming environments, because libpq, its external API, is very well-designed and very well-documented. This means that writing utilities which plug into PostgreSQL is very easy and convenient, which makes the database more versatile and a better fit in an analytics stack. On many occasions I have knocked up a quick program in C or C which connects to PostgreSQL, pulls some data out and does some heavy calculations on it, e. g. using multithreading or special CPU instructions - stuff the database itself is not suitable for. I have also written C programs which use setuid to allow normal users to perform certain administrative tasks in PostgreSQL. It is very handy to be able to do this quickly and neatly. MS SQL Servers external language bindings vary. Sometimes you have to install extra drivers. Sometimes you have to create classes to store the data you are querying, which means knowing at compile time what that data looks like. Most importantly, the documentation is a confusing, tangled mess, which makes getting this done unnecessarily time-consuming and painful. 1.11. Documentation Data analytics is all about being a jack of all trades. We use a very wide variety of programming languages and tools. (Off the top of my head, the programmingscripting languages I currently work with are PHP, JavaScript, Python, R, C, C, Go, three dialects of SQL, PLPGSQL and Bash.) It is hopelessly unrealistic to expect to learn everything you will need to know up front. Getting stuff done frequently depends on reading documentation. A well-documented tool is more useful and allows analysts to be more productive and produce higher-quality work. PostgreSQLs documentation is excellent. Everything is covered comprehensively but the documents are not merely reference manuals ndash they are full of examples, hints, useful advice and guidance. If you are an advanced programmer and really want to get stuck in, you can also simply read PostgreSQLs source code, all of which is openly and freely available. The docs also have a sense of humour: The first century starts at 0001-01-01 00:00:00 AD, although they did not know it at the time. This definition applies to all Gregorian calendar countries. There is no century number 0, you go from -1 century to 1 century. If you disagree with this, please write your complaint to: Pope, Cathedral Saint-Peter of Roma, Vatican. MS SQL Servers documentation is all on MSDN, which is an unfriendly, sprawling mess. Because Microsoft is a large corporation and its clients tend to be conservative and humourless, the documentation is business appropriate ndash i. e. officious, boring and dry. Not only does it lack amusing references to the historical role of Catholicism in the development of date arithmetic, it is impenetrably stuffy and hidden behind layers of unnecessary categorisation and ostentatiously capitalised official terms. Try this: go to the product documentation page for MS SQL Server 2012 and try to get from there to something useful. Or try reading this gem (not cherry-picked, I promise): A report part definition is an XML fragment of a report definition file. You create report parts by creating a report definition, and then selecting report items in the report to publish separately as report parts. Has the word report started to lose its meaning yet (And, of course, MS SQL Server is closed source, so you cant look at the source code. Yes, I know source code is not the same as documentation, but it is occasionally surprisingly useful to be able to simply grep the source for a relevant term and cast an eye over the code and the comments of the developers. Its easy to think of our tools as magical black boxes and to forget that even something as huge and complex as an RDBMS engine is, after all, just a list of instructions written by humans in a human-readable language.) 1.12. Logging thats actually useful MS SQL Servers logs are spread across several places - error logs, Windows event log, profiler logs, agent logs and setup log. To access these you need varying levels of permissions and you have to use various tools, some of which are GUI-only. Maybe things like Splunk can help to automate the gathering and parsing of these logs. I havent tried, nor do I know anyone else who has. Google searches on the topic produce surprisingly little information, surprisingly little of which is of any use. PostgreSQLs logs, by default, are all in one place. By changing a couple of settings in a text file, you can get it to log to CSV (and since were talking about PostgreSQL, its proper CSV, not broken CSV). You can easily set the logging level anywhere from dont bother logging anything to full profiling and debugging output. The documentation even contains DDL for a table into which the CSV-format logs can be conveniently imported. You can also log to stderr or the system log or to the Windows event log (provided youre running PostgreSQL in Windows, of course). The logs themselves are human-readable and machine-readable and contain data likely to be of great value to a sysadmin. Who logged in and out, at what times, and from where Which queries are being run and by whom How long are they taking How many queries are submitted in each batch Because the data is well-formatted CSV, it is trivially easy to visualise or analyse it in R or PostgreSQL itself or Pythons matplotlib or whatever you like. Overlay this with the wealth of information that Linux utilities like top, iotop and iostat provide and you have easy, reliable access to all the server telemetry you could possibly need. 1.13. Support How is PostgreSQL going to win this one Everyone knows that expensive flagship enterprise products by big commercial vendors have incredible support, whereas free software doesnt have any Of course, this is nonsense. Commercial products have support from people who support it because they are paid to. They do the minimum amount necessary to satisfy the terms of the SLA. As I type this, some IT professionals I know are waiting for a major hardware vendor to help them with a performance issue in a 40,000 server. Theyve been discussing it with the vendor for weeks theyve spent time and effort running extensive tests and benchmarks at the vendors request and so far the vendors reaction has been a mixture of incompetence, fecklessness and apathy. The 40,000 server is sitting there performing very, very slowly, and its users are working 70-hour weeks to try to stay on schedule. Over the years I have seen many, many problems with expensive commercial software ndash everything from bugs to performance issues to incompatibility to insufficient documentation. Sometimes these problems cause a late night or a lost weekend for the user sometimes they cause missed deadlines and angry clients sometimes it goes as far as legal and reputational risk. Every single time, the same thing happens: the problem is fixed by the end users, using a combination of blood, sweat, tears, Google and late nights. I have never seen the vendor swoop to the rescue and make everything OK. So what is the support for PostgreSQL like On the two occasions I have asked the PostgreSQL mailing list for help, I have received replies from Tom Lane within 24 hours. Take a moment to click on the link and read the wiki - the guy is not just a lead developer of PostgreSQL, hes a well-known computer programmer. Needless to say, his advice is as good as advice gets. On one of the occasions, where I asked a question about the best way to implement cross-function call persistent memory allocation, Lane replied with the features of PostgreSQL I should study and suggested solutions to my problem ndash and for good measure he threw in a list of very good reasons why my tentative solution (a C static variable) was rubbish. You cant buy that kind of support, but you can get it from a community of enthusiastic open source developers. Oh, did I mention that the total cost of the database software and the helpful advice and recommendations from the acclaimed programmer was 0.00 Note that by support I mean help getting it to work properly. Some people (usually people who dont actually use the product) think of support contracts more in terms of legal coverage ndash theyre not really interested in whether help is forthcoming or not, but they like that theres someone to shout at and, more importantly, blame. I discuss this too, here . (And if youre really determined to pay someone to help you out, you can of course go to any of the organisations which provide professional support for PostgreSQL. Unlike commercial software vendors, whose support functions are secondary to their main business of selling products, these organisations live or die by the quality of the support they provide, so it is very good.) 1.14. Flexible, scriptable database dumps Ive already talked about scriptability, but database dumps are very important, so they get their own bit here. PostgreSQLs dump utility is extremely flexible, command-line driven (making it easily automatable and scriptable) and well-documented (like the rest of PostgreSQL). This makes database migration, replication and backups ndash three important and scary tasks ndash controllable, reliable and configurable. Moreover, backups can be in a space-effecient compressed format or in plain SQL, complete with data, making them both human-readable and executable. A backup can be of a single table or of a whole database cluster. The user gets to do exactly as he pleases. With a little work and careful selection of options, it is even possible to make a DDL-only plain SQL PostgreSQL backup executable in a different RDBMS. MS SQL Servers backups are in a proprietary, undocumented, opaque binary format. 1.15. Reliability Neither PostgreSQL nor MS SQL Server are crash-happy, but MS SQL Server does have a bizarre failure mode which I have witnessed more than once: its transaction logs become enormous and prevent the database from working. In theory the logs can be truncated or deleted but the documentation is full of dire warnings against such action. PostgreSQL simply sits there working and getting things done. I have never seen a PostgreSQL database crash in normal use. PostgreSQL is relatively bug-free compared to MS SQL Server. I once found a bug in PostgreSQL 8.4 ndash it was performing a string distance calculation algorithm wrongly. This was a problem for me because I needed to use the algorithm in some fuzzy deduplication code I was writing for work. I looked up the algorithm on Wikipedia, gained a rough idea of how it works, found the implementation in the PostgreSQL source code, wrote a fix and emailed it to one of the PostgreSQL developers. In the next release of PostgreSQL, version 9.0, the bug was fixed. Meanwhile, I applied my fix to my own installation of PostgreSQL 8.4, re-compiled it and kept working. This will be a familiar story to many of the users of PostgreSQL, and indeed any large piece of open source software. The community benefits from high-quality free software, and individuals with the appropriate skills do what they can to contribute. Everyone wins. With a closed-source product, you cant fix it yourself ndash you just raise a bug report, cross your fingers and wait. If MS SQL Server were open source, section 1.1 above would not exist, because I (and probably thousands of other frustrated users) would have damn well written a proper CSV parser and plumbed it in years ago. 1.16. Ease of installing and updating Does this matter Well, yes. Infrastructure flexibility is more important than ever and that trend will only continue. Gone are the days of the big fat server install which sits untouched for years on end. These days its all about fast, reliable, flexible provisioning and keeping up with cutting-edge features. Also, as the saying goes, time is money. I have installed MS SQL Server several times. I have installed PostgreSQL more times than I can remember - probably at least 50 times. Installing MS SQL Server is very slow. It involves immense downloads (who still uses physical install media) and lengthy, important-sounding processes with stately progress bars. It might fail if you dont have the right version of. NET or the right Windows service pack installed. Its the kind of thing your sysadmin needs to find a solid block of time for. Installing PostgreSQL the canonical way ndash from a Linux repo ndash is as easy as typing a single command, like this: How long does it take I just tested this by spinning up a cheap VM in the cloud and installing PostgreSQL using the above command. It took 16 seconds . Thats the total time for the download and the install. As for updates, any software backed by a Linux repo is trivially easily patched and updated by pulling updates from the repo. Because repos are clever and PostgreSQL is not obscenely bloated, downloads are small and fast and application of updates is efficient. I dont know how easy MS SQL Server is to update. I do know that a lot of production MS SQL Server boxes in certain organisations are still on version 2008 R2 though. 1.17. The contrib modules As if the enormous feature set of PostgreSQL is not enough, it comes with a set of extensions called contrib modules. There are libraries of functions, types and utilities for doing certain useful things which dont quite fall into the core feature set of the server. There are libraries for fuzzy string matching, fast integer array handling, external database connectivity, cryptography, UUID generation, tree data types and loads, loads more. A few of the modules dont even do anything except provide templates to allow developers and advanced users to develop their own extensions and custom functionality. Of course, these extensions are trivially easy to install. For example, to install the fuzzystrmatch extension you do this: 1.18. Its free PostgreSQL is free as in freedom and free as in beer. Both types of free are extremely important. The first kind, free as in freedom, means PostgreSQL is open-source and very permissively licensed. In practical terms, this means that you can do whatever you want with it, including distributing software which includes it or is based on it. You can modify it in whatever way you see fit, and then you can distribute the modifications to whomever you like. You can install it as many times as you like, on whatever you like, and then use it for any purpose you like. The second kind, free as in beer, is important for two main reasons. The first is that if, like me, you work for a large organisation, spending that organisations money involves red tape. Red tape means delays and delays sap everyones energy and enthusiasm and suppress innovation. The second reason is that because PostgreSQL is free, many developers, experimenters, hackers, students, innovators, scientists and so on (the brainy-but-poor crowd, essentially) use it, and it develops a wonderful community. This results in great support (as I mentioned above ) and contributions from the intellectual elite. It results in a better product, more innovation, more solutions to problems and more time and energy spent on the things that really matter. 2. The counterarguments For reasons which have always eluded me, people often like to ignore all the arguments and evidence above and try to dismiss the case for PostgreSQL using misconceptions, myths, red herrings and outright nonsense. Stuff like this: 2.1. But a big-name vendor provides a safety net No it doesnt. This misconception is a variant of the old adage no-one ever got fired for buying IBM. Hilariously, if you type that into Google, the first hit is the Wikipedia article on fear, uncertainty and doubt - and even more hilariously, the first entry in the examples section is Microsoft. I promise I did not touch the Wikipedia article, I simply found it like that. In client-serving data analytics, you just have to get it right. If you destroy your reputation by buggering up an important job, your software vendor will not build you a new reputation. If you get sued, then maybe you can recover costs from your vendor - but only if they did something wrong. Microsoft isnt doing anything technically wrong with MS SQL Server, theyre simply releasing a terrible product and being up front about how terrible it is. The documentation admits its terrible. It works exactly as designed the problem is that the design is terrible. You cant sue Microsoft just because you didnt do your due diligence when you picked a database. Even if you somehow do successfully blame the vendor, you still have a messed up job and an angry client, who wont want to hear about MS SQL Servers unfortunate treatment of UTF-16 text as UCS-2, resulting in truncation of a surrogate pair during a substring operation and subsequent failure to identify an incriminating keyword. At best they will continue to demand results (and probably a discount) at worst, they will write you off as incompetent ndash and who could blame them, when you trusted their job to a RDBMS whose docs unapologetically acknowledge that it might silently corrupt your data Since the best way to minimise risk is to get the job done right, the best tool to use is the one which is most likely to let you accomplish that. In this case, thats PostgreSQL. 2.2. But what happens if the author of PostgreSQL dies Same thing that happens if the author of MS SQL Server dies ndash nothing. Also, needless to say, the author of PostgreSQL is as meaningless as the author of MS SQL Server. Theres no such thing. A senior individual with an IT infrastructure oversight role actually asked me this question once (about Hadoop, not PostgreSQL). There just seems to be a misconception that all open-source software is written by a loner who lives in his mums basement. This is obviously not true. Large open source projects like PostgreSQL and Hadoop are written by teams of highly skilled developers who are often commercially sponsored. At its heart, the development model of PostgreSQL is just like the development model of MS SQL Server: a large team of programmers is paid by an organisation to write code. There is no single point of failure. There is at least one key difference, though: PostgreSQLs source code is openly available and is therefore reviewed, tweaked, contributed to, improved and understood by a huge community of skilled programmers. Thats one of the reasons why its so much better. Crucially, because open-source software tends to be written by people who care deeply about its quality (often because they have a direct personal stake in ensuring that the software works as well as possible), it is often of the very highest standard (PostgreSQL, Linux, MySQL, XBMC, Hadoop, Android, VLC, Neo4JS, Redis, 7Zip, FreeBSD, golang, PHP, Python, R, Nginx, Apache, node. js, Chrome, Firefox. ). On the other hand, commercial software is often designed by committee, written in cube farms and developed without proper guidance or inspiration (Microsoft BOB, RealPlayer, Internet Explorer 6, iOS Maps, Lotus Notes, Windows ME, Windows Vista, QuickTime, SharePoint. ) 2.3. But open-source software isnt securereliabletrustworthyenterprise-readyetc Theres no kind way to say this: anyone who says such a thing is very ignorant, and you should ignore them ndash or, if youre feeling generous, educate them. Well, I guess Im feeling generous: Security: the idea that closed-source is more secure is an old misconception, for many good reasons which I will briefly summarise (but do read the links ndash theyre excellent): secrecy isnt the same as security an open review process is more likely to find weaknesses than a closed one properly reviewed open source software is difficult or impossible to build a back door into. If you prefer anecdotal evidence to logical arguments, consider that Microsoft Internet Explorer 6, once a flagship closed-source commercial product, is widely regarded as the least secure software ever produced, and that Rijndael, the algorithm behind AES, which governments the world over use to protect top secret information, is an open standard. In any case, relational databases are not security software. In the IT world, security is a bit like support our troops in the USA or think of the children in the UK ndash a trump card which overrules all other considerations, including common sense and evidence. Dont fall for it. Reliability: Windows was at one point renowned for its instability, although these days things are much better. (Supposedly, Windows 9x would spontaneously crash when its internal uptime counter, counting in milliseconds, exceeded the upper bound of an unsigned 32-bit integer, i. e. after 2 32 milliseconds or about 49.7 days. I have always wanted to try this.) Linux dominates the server space, where reliability is key, and Linux boxes routinely achieve uptimes measured in years. Internet Explorer has always (and still does) failed to comply with web standards, causing websites to break or function improperly the leaders in the field are the open-source browsers Chrome and Firefox. Lotus Notes is a flaky, crash-happy, evil mess Thunderbird just works. And I have more than once seen MS SQL Server paralyse itself by letting transaction log files blow up, something PostgreSQL does not do. Trustworthiness: unless youve been living under a rock for the past couple of years, you know who Edward Snowden is. Thanks to him, we know exactly what you cannot trust: governments and the large organisations they get their hooks into. Since Snowden went public, it is clear that NSA back doors exist in a vast array of products, both hardware and software, that individuals and organisations depend on to keep their data secure. The only defence against this is open code review. The only software that can be subjected to open code review is open source software. If you use proprietary closed-source software, you have no way of knowing what it is really doing under the hood. And thanks to Mr. Snowden, we now know that there is an excellent chance it is giving your secrets away. At the time of writing, 485 of the top 500 supercomputers in the world run on Linux. As of July 2014, Nginx and Apache, two open-source web servers, power over 70 of the million busiest sites on the net. The computers on the International Space Station (the most expensive single man-made object in existence) were moved from Windows to Linux in 2013 in an attempt to improve stability and reliability. The back-end database of Skype (ironically now owned by Microsoft) is PostgreSQL. GCHQ recently reported that Ubuntu Linux is the most secure commonly-available desktop operating system. The Large Hadron Collider is the worlds largest scientific experiment. Its supporting IT infrastructure, the Worldwide LHC Computing Grid, is the worlds largest computing grid. It handles 30 PB of data per year and spans 36 countries and over 170 computing centres. It runs primarily on Linux. Hadoop, the current darling of many large consultancies looking to earn Big Data credentials, is open-source. Red Hat Enterprise Linux CEntOS (Community Enterprise OS) SUSE Linux Enterprise Server Oracle Linux IBM Enterprise Linux Server etc. The idea that open-source software is not for the enterprise is pure bullshit. If you work in tech for an organisation which disregards open source, enjoy it while it lasts. They wont be around for long. 2.4. But MS SQL Server can use multiple CPU cores for a single query This is an advantage for MS SQL Server whenever youre running a query which is CPU-bound and not IO-bound. In real-life data analytics this happens approximately once every three blue moons. On those very rare, very specific occasions when CPU power is truly the bottleneck, you almost certainly should be using something other than an RDBMS. RDBMSes are not for number crunching. This advantage goes away when a server has to do many things at once (as is almost always the case). PostgreSQL uses multiprocessing ndash different connections run in different processes, and hence on different CPU cores. The scheduler of the OS takes care of this. Also, I suspect this query parallelism is what necessitates the merge method which MS SQL Server custom aggregate assemblies are required to implement bits of aggregation done in different threads have to be combined with each other, MapReduce-style. I further suspect that this mechanism is what prevents MS SQL Server aggregates from accepting ORDER BY clauses. So, congratulations ndash you can use more than one CPU core, but you cant do a basic string roll-up. 2.5. But I have MS SQL Server skills, not PostgreSQL skills Youd rather stick with a clumsy, awkward, unreliable system than spend the trivial amount of effort it takes to learn a slightly different dialect of a straightforward querying language Well, just hope you never end up in a job interview with me. 2.6. But a billion Microsoft users cant all be wrong This is a real-life quotation as well, from a senior data analyst I used to work with. I replied well there are 1.5 billion Muslims and 1.2 billion Catholics. They cant all be right. Ergo, a billion people most certainly can be wrong. (In this particular case, 2.7 billion people are wrong.) 2.7. But if it were really that good then it wouldnt be free People actually say this too. I feel sorry for these people, because they are unable to conceive of anyone doing anything for any reason other than monetary gain. Presumably they are also unaware of the existence of charities or volunteers or unpaid bloggers or any of the other things people do purely out of a desire to contribute or to create something or simply to take on a challenge. This argument also depends on an assumption that open source development has no benefit for the developer, which is nonsense. The reason large enterprises open-source their code and then pay their teams to continue working on it is because doing so benefits them. If you open up your code and others use it, then you have just gained a completely free source of bug fixes, feature contributions, code review, product testing and publicity. If your product is good enough, it is used by enough people that it starts having an influence on standards, which means broader industry acceptance. You then have a favoured position in the market as a provider of support and deployment services for the software. Open-sourcing your code is often the most sensible course of action even if you are completely self-interested. As a case in point, here I am spending my free time writing a web page about how fabulous PostgreSQL is and then paying my own money to host it. Perhaps Teradata or Oracle are just as amazing, but theyre not getting their own pages because I cant afford them, so I dont use them. 2.8. But youre biased No, I have a preference. The whole point of this document is to demonstrate, using evidence, that this preference is justified. If you read this and assume that just because I massively prefer PostgreSQL I must be biased, that means you are biased, because you have refused to seriously consider the possibility that it really is better. If you think theres actual evidence that I really am biased, let me know. 2.9. But PostgreSQL is a stupid name This one is arguably true its pretty awkward. It is commonly mispronounced, very commonly misspelt and almost always incorrectly capitalised. Its a good job that stupidness of name is not something serious human beings take into account when theyre choosing industrial software products. That being said, MS SQL Server is literally the most boring possible name for a SQL Server provided by MS. It has anywhere from six to eight syllables, depending on whether or not you abbreviate Microsoft and whether you say it sequel or ess queue ell, which is far too many syllables for a product name. Microsoft has a thing for very long names though ndash possibly its greatest achievement ever is Microsoft WinFX Software Development Kit for Microsoft Pre-Release Windows Operating System Code-Named Longhorn, Beta 1 Web Setup I count 38 syllables. Beeindruckend. 2.10. But SSMS is better than PGAdmin Its slicker, sure. Its prettier. It has code completion, although I always turn that off because it constantly screws things up, and for every time it helps me out with a field or table name, theres at least one occasion when it does something mental, like auto-correcting a common SQL keyword like table to a Microsoft monstrosity like TABULATIONNONTRIVIALDISCOMBOBULATEDMACHIAVELLIANGANGLYONID or something. For actually executing SQL and looking at the results in a GUI, PGAdmin is fine. Its just not spectacular. SSMS is obviously Windows-only. PGAdmin is cross-platform. This is actually quite convenient. You can run PGAdmin in Windows, where you have all your familiar stuff ndash Office, Outlook etc. ndash whilst keeping the back end RDBMS in Linux. This gets you the best of both worlds (even an open source advocate like me admits that if youre a heavy MS Office user, there is no serious alternative). Several guys I work with do this. One point in SSMSs favour is that if you run several row-returning statements in a batch, it will give you all the results. PGAdmin returns only the last result set. This can be a drag when doing data analytics, where you often want to simultaneously query several data sets and compare the results. Theres another thing though: psql. This is PostgreSQLs command-line SQL interface. Its really, really good. It has loads of useful catalog-querying features. It displays tabular data intelligently. It has tab completion which, unlike SSMSs code completion, is actually useful, because it is context sensitive. So, for example, if you type DROP SCHEMA t and hit tab, it will suggest schema names starting with t (or, if there is only one, auto-fill it for you). It lets you jump around in the file system and use ultra-powerful text editors like vim inline. It automatically keeps a list of executed commands. It provides convenient, useful data import and export functionality, including the COPY TO PROGRAM feature which makes smashing use of pipes and command-line utilities to provide another level of flexibility and control of data. It makes intelligent use of screen space. It is fast and convenient. You can use it over an SSH connection, even a slow one. Its only serious disadvantage is that it is unsuitable for people who want to be data analysts, but are scared of command lines and typing on a keyboard. 2.11. But MS SQL Server can import straight from Excel Yes. So what Excel can output to CSV (in a rare moment of sanity, Microsoft made Excels CSV export code work properly) and PostgreSQL can import CSV. Admittedly, its an extra step. Is the ability to import straight from Excel a particularly important feature in an analytics platform anyway 2.12. But PostgreSQL is slower than MS SQL Server A more accurate rephrasing would be MS SQL Server is slightly more forgiving if you dont know what youre doing. For certain operations, PostgreSQL is definitely slower than MS SQL Server ndash the easiest example is probably COUNT(). which is (I think) always instant in MS SQL Server and in PostgreSQL requires a full table scan (this is due to the different concurrency models they use). PostgreSQL is slow out-of-the box because its default configuration uses only a tiny amount of system resources ndash but any system being used for serious work has been tuned properly, so raw out-of-the-box performance is not a worthwhile thing to argue about. I once saw PostgreSQL criticised as slow because it was taking a long time to do some big, complex regex operations on a large table. But everyone knows that regex operations can be very computationally expensive, and in any case, what was PostgreSQL being compared to Certainly not the MS SQL Server boxes, which couldnt do regexes. PostgreSQLs extensive support for very clever indexes, such as range type indexes and trigram indexes, makes it orders of magnitude faster than MS SQL Server for a certain class of operations. But only if you know how to use those features properly. The immense flexibility you get from the great procedural language support and the clever data types allows PostgreSQL-based solutions to outperform MS SQL Server-based solutions by orders of magnitude. See my earlier example . In any case, the argument about speed is never only about computer time it is about developer time too. Thats why high-level languages like PHP and Python are very popular, despite the fact that C kicks the shit out of them when it comes to execution speed. They are slower to run but much faster to use for development. Would you prefer to spend an hour writing maintainable, elegant SQL followed by an hour of runtime, or spend three days writing buggy, desperate workarounds followed by 45 minutes of runtime 2.13. But you never mentioned such-and-such feature of MS SQL Server As I said in the banner and the intro. I am comparing these databases from the point of view of a data analyst, because Im a data analyst and I use them for data analysis. I know about SSRS, SSAS, in-memory column stores and so on, but I havent mentioned them because I dont use them (or equivalent features). Yes, this means this is not a comprehensive comparison of the two databases, and I never said it would be. It also means that if you care mostly about OLTP or data warehousing, you might not find this document very helpful. 2.14. But Microsoft has open-sourced. NET Yeah, mere hours after I wrote all about how theyre a vendor lock-in monster and are anti-open source. Doh. However, lets look at this in context. Remember the almighty ruckus when the Office Open XML standard was being created Microsoft played every dirty trick in the book to ensure that MS Office wouldnt lose its dominance. Successfully, too ndash the closest alternative, LibreOffice, is still not a viable option, largely because of incompatibility with document formats. The OOXML standard that was finally pushed through is immense, bloated, ambiguous, inconsistent and riddled with errors. That debacle also started with an apparent gesture toward open standards on Microsofts part. If that seems harsh or paranoid, lets remember that this is an organisation that has been in legal trouble with both the USA and the EU for monopolistic and anticompetitive behaviour and abuse of market power, in the latter case being fined almost half a billion Euros. Then theres the involvement in SCOs potentially Linux-killing lawsuit against IBM. When Steve Ballmer was CEO he described Linux as a cancer (although Ballmer also said Theres no chance that the iPhone is going to get any significant market share. No chance, so maybe he just likes to talk nonsense). Microsoft has a long-established policy of preferring conquest to cooperation. So, if they play nice for the next few years and their magnanimous gesture ushers in a new era of interoperability, productivity and harmony, I (and millions of developers who want to get on with creating great things instead of bickering over platforms and standards) will be over the moon. For now, thinking that MS has suddenly become all warm and fuzzy would just be naive. 2.15. But youre insultingI dont like your toneyou come across as angryyou sound like a fanboythis is unprofessionalthis is a rant This page is unprofessional by definition ndash Im not being paid to write it. That also means I get to use whatever tone I like, and I dont have to hide the way I feel about things. I hope you appreciate the technical content even if you dont like the way I write if my tone makes this document unreadable for you, then I guess Ive lost a reader and youve lost a web page. Cest la vie.

Comments