Thursday 2 November 2017

Moving Media Postgresql


In un database di transazioni che abbracciano 1.000 s di soggetti oltre i 18 mesi, vorrei eseguire una query per gruppo ogni possibile periodo di 30 giorni dalla EntityID con una somma dei loro valori di transazione e conte di loro transazioni in quel periodo di 30 giorni, e restituire i dati in un modo che io possa poi interrogare contro. Dopo un sacco di test, questo codice compie gran parte di ciò che voglio: E io userà in una query strutturata più qualcosa di simile: Il caso che questa copertura interrogazione doesnt è quando i conti di transazione sarebbero estendersi su più mesi, ma ancora essere entro 30 giorni di ciascun altro. E 'questo tipo di query possibile con Postgres Se è così, accolgo con favore qualsiasi ingresso. Molti degli altri argomenti discutere in esecuzione aggregati, non a rotazione. Lo script CREATE TABLE: uscita ideale includerebbe SUM (quantità) e COUNT () di tutte le operazioni nel corso di un periodo di 30 giorni a rotazione. Vedere questa immagine, ad esempio: La data di evidenziazione verde indica che cosa è essere inclusi dalla mia domanda. La fila evidenziazione gialla indica record quello che vorrebbe diventare parte del set. Con ogni possibile periodo di 30 giorni dalla EntityID si intende il periodo può iniziare in qualsiasi giorno, quindi 365 possibili periodi in un (non bisestile) dell'anno Oppure solo prendere in considerazione giorni con una transazione reale come inizio di un periodo individualmente per ogni EntityID. In entrambi i casi, si prega di fornire la vostra definizione della tabella, la versione Postgres, alcuni dati di esempio e il risultato previsto per il campione. ndash Erwin Brandstetter 20 luglio 15 a 7:18 In teoria, volevo dire ogni giorno, ma in pratica non vi è alcuna necessità di prendere in considerazione giorni dove non ci sono transazioni. I39ve postato la definizione dei dati di esempio e da tavolo. ndash tufelkinder 20 luglio 15 alle 14:50 Così si vuole accumulare righe della stessa EntityID in una finestra di 30 giorni a partire da ogni transazione reale. Ci può essere più transazioni per lo stesso (TransDate, EntityID), o è quella combinazione unica definita tua definizione di tabella non ha alcun vincolo UNIQUE o PK, ma i vincoli sembrano mancare. ndash Erwin Brandstetter 20 Luglio 15 in 15:44 La query avete Si potrebbe semplificare la query utilizzando una clausola finestra, ma questo è solo accorciare la sintassi, non cambiando il piano di query. Inoltre utilizzando il conteggio leggermente più veloce (). dal momento che id è certamente definita NOT NULL e non avete bisogno di ORDER BY EntityID dal momento che già PARTITION BY EntityID È possibile semplificare ulteriormente, però: Non aggiungere ORDER BY alla definizione finestra a tutti, non è rilevante per la query. Allora non avete bisogno di definire una cornice finestra personalizzata, sia: più semplice, più veloce, ma ancora solo una versione migliore di quello che hai. con mesi statici. La query si potrebbe desiderare non è chiaramente definito, in modo da Ill costruire su questi presupposti: Count transazioni e quantità per ogni periodo di 30 giorni entro il primo e l'ultimo di transazione di qualsiasi EntityID. Escludere iniziali e finali periodi senza attività, ma includono tutti i possibili periodi di 30 giorni all'interno di tali limiti esterni. Questo elenca tutti i periodi di 30 giorni per ogni EntityID con i tuoi inerti e con TransDate essere il primo giorno (incl.) Del periodo. Per ottenere i valori per ogni singola riga si uniscono alla tabella di base ancora una volta. La difficoltà di base è la stessa come discusso qui: La definizione telaio di una finestra non può dipendere valori della riga corrente. La query si vuole realmente Dopo l'aggiornamento domanda e discussione: Accumula righe della stessa EntityID in una finestra di 30 giorni a partire da ogni transazione reale. Dal momento che i dati sono distribuiti scarsamente, dovrebbe essere più efficiente per eseguire un self-join con una condizione di gamma. tanto più che Postgres 9.1 non ha LATERALE si unisce, ancora: una finestra a rotazione potrebbe aver senso solo (rispetto alle prestazioni) con i dati per quasi tutti i giorni. Questo fa i duplicati non aggregate su (TransDate, EntityID) al giorno, ma tutte le righe dello stesso giorno sono sempre inclusi nella finestra di 30 giorni. Per un grande tavolo, un indice di copertura come questo potrebbe aiutare un po ': L'ultima colonna quantità è utile solo se si ottiene scansioni indice solo fuori di esso. Altrimenti cadere. Ma la sua non intenzione di essere utilizzato mentre si seleziona l'intera tabella in ogni caso. Sarebbe supportare query per un piccolo subset. Beta versione Enodo Score utilizza una vasta gamma di API a disposizione del pubblico e di condivisione dei dati partnership alla fonte i dati. I nostri dati demografici ed economici viene generalmente dalla statunitense Census Bureau, mentre i nostri dati di mercato appartamento è raccolto principalmente da fonti pagati e condivisione dei dati partnership con aziende leader del settore. Noi facciamo di tutto per pulire, standardizzare e formattare i dati prima che sia usato per l'analisi predittiva. Dato che lo sviluppo della piattaforma progredisce, una porzione più ampia dei nostri dati arriverà direttamente dagli utenti attraverso upload diretti ed integrazioni software di gestione immobiliare, garantendo la coerenza e l'accuratezza delle informazioni. banca dati Enodo punteggi è progettato per raccogliere le operazioni di proprietà di dati nonché i dati sull'utilizzo della piattaforma stessa, o metadati, da ogni utente. Questi dati vengono poi utilizzati per addestrare e perfezionare i nostri algoritmi predittivi. Sappiamo quanto sia importante dati in vista della vera e propria industria immobiliare Ecco perché weve progettato la nostra piattaforma per funzionare come un CRM cloud-based (ad esempio, Salesforce). dati Everyones è completamente sicuro in conto proprio. Ogni volta che un immobile è caricato o analizzata da un utente, viene creata una copia di quella proprietà, con un ID univoco che è accessibile solo da tale account utenti. Per i nostri algoritmi predittivi, i dati specifici di ogni singolo utente non è importante. I, dati anonimi collettivi provenienti da tutti gli utenti è dove si trova l'valore Vero, e questo è il dato che i nostri algoritmi utilizzano per migliorare continuamente le previsioni e creare lungimiranti proiezioni di mercato. Enodo squadra segna Data Science è stato in grado di raggiungere più di 93 previsioni accurate di affitto come una funzione di indirizzo della proprietà, il numero di camere da letto, numero di bagni, unità di metratura, servizi (con circa 200 servizi diversi sono contabilizzati a livello nazionale), e single vs tipo di proprietà multifamiliari. Facciamo in modo tale accuratezza testando le nostre previsioni su dati storici e vagliare le nostre previsioni direttamente con gli investitori, gli sviluppatori e gli intermediari che operano nel settore multifamiliari. Sulla base di quanto weve sentito da utenti interessati, Enodo Score è ampio applicabilità a molti segmenti del settore. Qui ci sono solo alcuni esempi: a valore aggiunto investitori - Gli investitori, come la possibilità di quantificare l'aumento di affittare da tutti i comfort in un investimento a valore aggiunto, e di analizzare rapidamente le nuove opportunità. In media, l'analisi di tutte le opportunità di investimento richiede circa 4,5 ore di raccolta di informazioni e di analisi - abbiamo bollire quel processo fino a meno di 10 minuti. Sviluppatori - La capacità di determinare quali mercati esporrà le migliori prestazioni degli investimenti, e per testare diverse miscele di unità e pacchetti di servizi all'interno di tali mercati, sembra essere l'aspetto più importante del prodotto per gli sviluppatori. Brokers - brokers di vendita di investimento come essere in grado di analizzare le strategie a valore aggiunto, immediatamente tirare composizioni, e oggettivamente confrontare le opportunità con un punteggio semplice. Molti hanno indicato che vorrebbero usarlo per sostenere le ipotesi di investimento quando hanno messo insieme opinioni mediatore di valore e di offerta memorandum. Istituti di credito - Molti istituti di credito ci hanno avvicinato sull'utilizzo del Enodo punteggio nello stesso modo in cui un punteggio FICO è attualmente utilizzato per quantificare il rischio di futuri inquilini. Come il Enodo Score quantifica rendimenti adeguati al rischio, abbiamo sicuramente vediamo il potenziale in questo mercato. Periti - periti commerciali spesso usano l'analisi di regressione per determinare l'impatto incrementale dei vari attributi di costruzione, ma raramente con una precisione comparabile. Molti hanno espresso interesse ad utilizzare Enodo Score come un modo oggettivo per eseguire il backup loro ipotesi di sottoscrizione di investimento. Per derivare il Enodo punteggio, i nostri progetti software in affitto, di occupazione, i costi operativi e valori di proprietà stimati in avanti sulla base delle demographicseconomics di ogni mercato, sconti flussi di cassa futuri per ogni proprietà torna a oggi al livello minimo di rendimento corretto per il rischio per il mercato, e poi confronta ogni propertys VAN su una base per unità, li classifica su scala 1-100 rispetto ad altre proprietà nello stesso mercato. Sappiamo quello che stai pensando - che suona abbastanza semplice. Che ci crediate o no, la sua realtà piuttosto difficile da ottenere tutti i dati necessari per fare questo su base continuativa, per non parlare di proiettare questi valori in avanti in base alle tendenze demografiche e macroeconomiche. Enodo Score copre tutti i mercati in tutti gli Stati Uniti. Che weve trovato è che non ci sono dati sufficienti per applicare i nostri algoritmi predittivi in ​​ogni mercato, ma la qualità e la quantità di dati disponibili nelle principali aree metropolitane portare ad una maggiore precisione predittiva in tali mercati. Alcuni mercati hanno così pochi dati multifamiliari che dobbiamo guardare in altri mercati simili per i punti dati sufficienti per fare una previsione accurata. Fortunatamente per i nostri clienti, i mercati con pochissimi dati tendono ad essere mercati in cui c'è ben poco che si svolgono multifamiliare di sviluppo. La maggior parte delle analisi completati sulla piattaforma sarà probabilmente nelle principali aree metropolitane, in cui i dati è abbondante e le nostre predicitons sono più accurate. Nelle notizie UIUX Developer Siamo alla ricerca di uno sviluppatore UIUX con 3-5 anni di esperienza per aiutare a sviluppare la nostra piattaforma di analisi predittiva immobiliare, Enodo Score. I candidati devono avere un elevato livello di competenza in user experience design di interfaccia utente e sviluppo web. Ciò includerà analisi di business, raccolta dei requisiti e la documentazione delle parti interessate e clienti, il wireframing, prototipazione, e il coordinamento dello sviluppo del prodotto con metodologia agile tra gli sviluppatori di back-end, gli scienziati di dati, ed esperti del settore immobiliare per fornire quattro funzionalità del prodotto stampa su un programma aggressivo tutto il 2017. un eccezionale livello di attenzione al dettaglio è un must. Un candidato ideale saprà migliori pratiche, li può documentare, e può lavorare con un team dinamico per garantire tutto lo sviluppo UIUX viene eseguita per tali norme. Responsabilità Analizzare sfide esperienza degli utenti e creare soluzioni di design in grado di soddisfare gli obiettivi di business analizzare i requisiti di dati delle applicazioni e dominio aziendale e regole di business, la comprensione del flusso di dati dalla sorgente allo schermo Create progetti centrati sull'utente prendendo in considerazione l'analisi di mercato, il feedback dei clienti, ei risultati usabilità riconoscere e prevedere casi d'uso e interazione con l'utente e applicazioni intuitive di progettazione per sostenere loro architettura dell'informazione e wireframing, e la costruzione di prototipi interattivi in ​​anticipo di funzionalità stampa assuma la responsabilità generale per la progettazione dell'interfaccia utente, incorporando l'usabilità, i flussi di lavoro completo, applicando standard, utilizzando vari strumenti per creare interfacce grafiche per le applicazioni web based lavorare direttamente con affari stakeholder, clienti, progettisti, sviluppatori, ingegneri e scienziati di dati per coordinare la realizzazione di applicazioni di specifiche e puntuali Rimani velocità sulle tendenze UIUX, come pure come standard aziendali e di settore Partecipa al test utente e ricerca stilistica al fine di conoscere Requisiti UIUX laurea in informatica o nel campo relativo 3 anni di interfaccia utente UX, grafica e visual design in un contextn aziendale o agenzia in grado di prendere un feedback costruttivo e iterare su disegni e le idee provenienti da più parti interessate con differenti opinioni comprensione ed esperienza nella progettazione user-centered processi pensatore creativo che può effettivamente innovare grandi idee e anche lavorare tutti i dettagli una passione per difendere UX e l'innovazione un'esperienza commovente disegni attraverso un agile wireframe processo di sviluppo e prototipazione esperienza specializzata nell'utilizzo di progettazione, wireframing, e utilizzare gli strumenti di caso eccellente capacità di capacità di progettazione l'interazione di codificare in modo rapido ed efficiente in HTML, CSS, JavaScript e l'esperienza passata con Vue. js, Leaflet. js, d3.js e altre librerie di visualizzazione dei dati L'esperienza con PythonDjango è un plus capacità di comunicare efficacemente con tutte le parti interessate, vale a dire gli sviluppatori tecnici, imprenditori e utenti Portfolio mostrando le vostre abilità di UI e UX è richiesto con applicazione CloseFull-Stack Python Developer Enodo Score è alla ricerca di un full-stack Python, PostgreSQL e HTMLCSSJavaScript sviluppatore di far parte del nostro movimento veloce, snella team di sviluppo prodotto a lavorare sul continuo sviluppo della nostra piattaforma di analisi predittiva immobiliare. Il ruolo prevede la consegna di affidabile, scalabile nuove funzionalità per gli utenti, sviluppato in Python utilizzando i quadri web2py e Vue. js. Si lavorerà con il team di sviluppo per progettare e fornire finito, di alta qualità, e le caratteristiche interessanti e prodotti in tempo. Responsabilità collaborare con team interdisciplinare di scienziati di dati, ingegneri del software e professionisti del settore immobiliare per progettare, sviluppare, testare unità, e supportano le nuove funzionalità Sforzatevi per l'alta qualità e l'uscita rapida attraverso l'uso di sviluppo agile del software di sintonia migliori pratiche delle prestazioni, test, refactoring, l'usabilità e l'automazione di supporto, manutenzione e funzionalità del software di aiuto documento mantenere la codifica, la conformità, e gli standard di sicurezza sul lavoro con altri clienti sullo sviluppo del software, miglioramenti, strumenti interni, e problemi di implementazione Manutenzione e la continuità del sostegno di soluzioni tecniche passate e future in modo proattivo imparare quadri di prodotti e base di codice Enodo Score è una società di avvio, e come tale le responsabilità di cui sopra potranno cambiare ed evolversi nel tempo. La flessibilità, la curiosità, una mentalità imprenditoriale e una forte etica del lavoro sono fondamentali per questo ruolo. E 'incoraggiante il fatto che tutti nel team di ricerca continuamente nuove tecnologie e opportunità di analisi per migliorare la piattaforma. La nostra piattaforma è costruita su Python e PostgreSQL, e utilizza quadri web2py e Vue. js. Ogni codice sviluppato dovrà essere in Python 2.7 e compatibile con la nostra base di codice esistente. Requisiti di 3 anni Python 2.7 e CSSHTMLJavaScript esperienza 2 anni di SQL, con esperienza di utilizzo di PostgreSQL Laurea in Informatica Laurea in Informatica o campo relativo a più Esperienza nell'utilizzo GitHub e solida conoscenza della versione del software di controllo L'esperienza con i framework Python come Django o web2py esperienza di lavoro con una società ad alta crescita SaaS è preferito Agile, magra, o simile sviluppo methodologiesexperience esperienza con Microsoft Azure o AWS un plus esperienza con Vue. js o di altre misure frontend Application Security (OWASP) auto-motivato Capire Web e in grado di lavorare in una piccola squadra con un minimo di supervisione esperienza con la scienza dei dati e analisi predittiva un plus ClosePostgreSQL vs MS SQL Server 0. che cosa significa tutto questo lavoro come analista di dati in una società globale di servizi professionali (quella che avete certamente sentito parlare). Ho fatto questo per circa un decennio. Ho trascorso quel decennio si occupano di dati, software di database, hardware, database di utenti di database, programmatori di database e metodi di analisi dei dati, quindi so un bel po 'di queste cose. Mi capita spesso di entrare in contatto con persone che sanno molto poco di queste cose ndash anche se alcuni di loro non si rendono conto. Nel corso degli anni ho discusso la questione di PostgreSQL vs MS SQL Server molte, molte volte. Un principio ben noto in che dice: se hai intenzione di farlo più di una volta, automatizzare esso. Questo documento è il mio modo di automatizzare quella conversazione. Se non diversamente indicato mi riferisco a PostgreSQL 9.3 e MS SQL Server 2014, anche se la mia esperienza con MS SQL Server è con le versioni 2008 R2 e il 2012 ndash per ragioni di equità e rilevanza voglio mettere a confronto l'ultima versione di PostgreSQL per l'ultima versione di MS SQL Server. Dove ho fatto affermazioni su MS SQL Server ho fatto del mio meglio per verificare che si applicano alla versione 2014 consultando Microsofts proprio ndash documentazione, anche se, per ragioni mi metterò a. Ho avuto anche fare affidamento in gran parte su Google, Stack Overflow e gli utenti di internet. Io proprio non so scientificamente rigoroso per fare un confronto come questo, quando io non sono uguale esperienza con entrambi i database, ma questo non è un esercizio accademico ndash suo confronto un mondo reale. Ho fatto del mio meglio onesto per ottenere i miei fatti su MS SQL Server destra ndash tutti sappiamo che è impossibile stronzate tutta Internet. Se scopro che Ive ha ottenuto qualcosa che non va, Ill risolvere il problema. Sto confrontando i due database dal punto di vista di un analista di dati. Forse MS SQL Server calci PostgreSQLs culo come un backend OLTP (anche se ne dubito), ma non è ciò che Im scrivere di qui, perché Im non un OLTP developerDBAsysadmin. Infine, vi è un indirizzo email in alto a destra. Non si prega di utilizzare, se lo si desidera farò del mio meglio per rispondere. NOTA BENE: tutte le opinioni soggettive in qui sono strettamente mio. 1. Perché PostgreSQL è molto, molto meglio di Server Ops, avviso MS SQL spoiler. Questa sezione è un confronto tra i due database in termini di caratteristiche rilevanti per analisi dei dati. 1.1. CSV supporto CSV è il modo standard de facto del movimento strutturato (cioè tabellare) dati in giro. Tutti gli RDBMS possono scaricare i dati in formati proprietari che nient'altro può leggere, che va bene per i backup, replica e simili, ma non serve a tutti per la migrazione dei dati dal sistema X al sistema Y. Una piattaforma di analisi dei dati deve essere in grado di guardare a dati provenienti da una grande varietà di sistemi e produrre uscite che possono essere letti da una vasta gamma di sistemi. In pratica, ciò significa che deve essere in grado di ingerire ed espellere CSV modo rapido, affidabile, ripetibile e indolore. Consente di non sottovalutare questo: una piattaforma di analisi dei dati che non possono gestire CSV robusta è una rotta, la responsabilità inutile. supporto PostgreSQLs CSV è di prim'ordine. La copia e copiare dai comandi supportano le specifiche descritte in RFC4180 (che è la cosa più vicina che c'è da uno standard ufficiale CSV), così come un gran numero di varianti e dialetti comuni e non-così-comuni. Questi comandi sono veloce e robusto. Quando si verifica un errore, danno messaggi di errore utile. È importante sottolineare che essi non silenziosamente corrotto, fraintendere o modificare i dati. Se PostgreSQL dice l'importazione ha funzionato, quindi ha funzionato correttamente. Al minimo segnale di un problema e si abbandona l'importazione e lancia un messaggio di errore utile. (Questo può sembrare esigente o scomodo, ma in realtà è un esempio di un principio di progettazione consolidata Ha senso:. Preferireste scoprire l'importazione è andato storto oggi, o un mese da oggi, quando il vostro cliente si lamenta che i risultati siano off) MS SQL Server può né l'importazione né l'esportazione CSV. La maggior parte delle persone non mi creda quando le dico questo. Poi, ad un certo punto, che vedono per se stessi. Di solito essi osservano qualcosa come: MS SQL Server in silenzio troncando un campo di testo MS SQL Server testo movimentazione andando male MS SQL Server lanciando un messaggio di errore perché non capisce citando o fuga (contrariamente alla credenza popolare, citando e la fuga di codifica non sono estensioni esotici a CSV. sono concetti fondamentali in letteralmente ogni specificazione dei dati di serializzazione leggibile. Non fidarsi di nessuno che non sa cosa sono queste cose) MS SQL server che esporta rotto, inutile documentazione orrendo CSV Microsofts. Come sono riusciti a complicare qualcosa di semplice come CSV Ciò è particolarmente sconcertante perché parser CSV sono banalmente facili da scrivere (ho scritto uno in C e plumbed in PHP un anno o due anni fa, perché non ero felice con la sua nativa CSV-handling funzioni. il tutto ha preso forse 100 righe di codice e tre ore ndash due dei quali sono stati spesi alle prese con SWIG., che era nuovo per me in quel momento). Se non mi creda, scarica questa correttamente formattato, conforme agli standard UTF-8 file CSV e utilizzare MS SQL Server per calcolare la lunghezza della stringa media (cioè il numero di caratteri) dell'ultima colonna in questo file (ha 50 colonne) . Vai avanti, provare. (La risposta siete alla ricerca di è esattamente 183,895.) Naturalmente, determinando questo è banalmente facile in PostgreSQL ndash infatti, il bit più in termini di tempo è la creazione di una tabella con 50 colonne per contenere i dati. Scarsa comprensione del CSV sembra essere endemica in Microsoft il file si romperà Access ed Excel troppo. Triste ma vero: alcuni programmatori di database che conosco recentemente trascorso un sacco di tempo e fatica a scrivere codice Python che igienizza CSV in modo da consentire MS SQL Server per importarlo. Non fossero in grado di evitare di modificare i dati effettivi in ​​questo processo, però. Questo è pazzo come spendere una fortuna in Photoshop e poi dover scrivere del codice personalizzato per farlo aprire un JPEG, solo per scoprire che l'immagine è stata modificata leggermente. 1.2. Ergonomia piattaforma di analisi ogni dato degno di nota è Turing completa, il che significa, più o meno, che uno di loro può fare qualcosa che nessun altro può fare. Non esiste una cosa come si può fare X in software A ma non si può fare X nel software B. Si può fare qualsiasi cosa in qualsiasi cosa ndash tutto ciò che varia è quanto sia difficile. Buoni strumenti fanno le cose che dovete fare semplici strumenti poveri li rendono difficile. Questo è quello che si riduce sempre a. (Questo è tutto concettualmente vero, se non letteralmente vero -. Per esempio, nessun RDBMS conosco può rendere la grafica 3D, ma uno di essi può emulare qualsiasi calcolo di una GPU in grado di eseguire.) PostgreSQL è chiaramente scritto da persone che realmente si preoccupano roba sempre fatto. MS SQL Server si sente come è stato scritto da persone che non hanno mai utilizzare effettivamente MS SQL Server per ottenere qualcosa. Ecco alcuni esempi di sostegno di questo: PostgreSQL supporta DROP TABLE IF EXISTS. che è il modo intelligente ed evidente di dire se questa tabella doesnt esiste, non fare nulla, ma se lo fa, sbarazzarsi di esso. Qualcosa di simile a questo: Ecco come si deve fare in MS SQL Server: Sì, è solo una riga in più di codice, a meno di notare il secondo parametro misterioso alla funzione OBJECTID. È necessario sostituire quello con NV a goccia una vista. La sua NP per una stored procedure. Io ho mai imparato tutte le diverse lettere per tutti i diversi tipi di oggetti di database (perché dovrei avere a) Si noti, inoltre, che il nome della tabella viene ripetuta inutilmente. Se la vostra concentrazione scivola per un attimo, i suoi morti facile da fare questo: vedere che cosa è successo lì Si tratta di una fonte affidabile di fastidiosi errori, perdite di tempo. PostgreSQL supporta GOCCIA SCHEMA CASCADE. che scende uno schema e tutti gli oggetti di database al suo interno. Questo è molto, molto importante per una robusta metodologia di consegna di analisi, dove tear-down-and-rebuild è il principio alla base della ripetibile, verificabile, il lavoro di analisi dei dati di collaborazione. Non esiste una struttura in MS SQL Server. È necessario eliminare tutti gli oggetti nello schema manualmente, e nel giusto ordine. perché se si tenta di eliminare un oggetto dal quale dipende un altro oggetto, MS SQL Server genera semplicemente un errore. Questo dà un'idea di come ingombrante questo processo può essere. PostgreSQL supporta CREATE TABLE AS. Un esempio di Wee: Questo significa che è possibile mettere in evidenza tutto, ma la prima linea ed eseguirlo, che è un compito utile e comune nello sviluppo di codice SQL. In MS SQL Server, la creazione delle tabelle va come questo, invece: Quindi, per eseguire l'istruzione SELECT pianura, è necessario commentare o rimuovere la punta nel. Sì, commentando le due linee è facile non questo è il punto. Il punto è che in PostgreSQL è possibile eseguire questa operazione semplice senza modificare il codice e in MS SQL Server non puoi, e che introduce un altro potenziale fonte di errori e fastidi. In PostgreSQL, è possibile eseguire il maggior numero di istruzioni SQL che vuoi in un unico lotto, purché youve finito ogni istruzione con un punto e virgola, è possibile eseguire qualsiasi combinazione di istruzioni che ti piace. Per l'esecuzione di processi in batch automatici o dati ripetibili costruisce o compiti di uscita, questo è di fondamentale importanza funzionalità. In MS SQL Server, una istruzione CREATE PROCEDURE non può apparire a metà di un batch di istruzioni SQL. Theres nessuna buona ragione per questo, il suo solo una limitazione arbitraria. Ciò significa che in più passaggi manuali sono spesso necessari per eseguire una grande serie di SQL. passaggi manuali aumentano il rischio e riducono l'efficienza. PostgreSQL supporta la clausola RETURNING, permettendo UPDATE. INSERT e DELETE per restituire valori da righe interessate. Questo è elegante e utile. MS SQL Server ha la clausola OUTPUT, che richiede una definizione della variabile tabella separata per funzionare. Questo è goffo e scomodo e costringe un programmatore di creare e mantenere il codice boilerplate inutili. PostgreSQL supporta stringa citando, in questo modo: Ciò è estremamente utile per la generazione di SQL dinamico in quanto (a) permette all'utente di evitare manuale noioso e poco affidabile citando e fuggire quando le stringhe letterali sono annidati e (b) in quanto gli editor di testo e IDE non tendono recogniise come delimitatore di stringa, l'evidenziazione della sintassi rimane funzionale anche nel codice SQL dinamico. PostgreSQL permette di usare linguaggi procedurali semplicemente presentando il codice per il motore di database si scrive codice procedurale in Python o Perl o R o JavaScript o una qualsiasi delle altre lingue supportate (vedi sotto) proprio accanto al vostro SQL, nello stesso script. Questo è conveniente, rapido, mantenibile, facile da esaminare, facile da riutilizzare e così via. In MS SQL Server, è possibile utilizzare il lento lingua grumoso,, imbarazzante T-SQL procedurale, oppure è possibile utilizzare un linguaggio per fare un assieme e caricarlo nel database. Questo significa che il codice è in due luoghi separati e si deve passare attraverso una serie di passaggi manuali basati su GUI per modificarlo. Rende il confezionamento fino tutte le tue cose in un unico luogo più duro e più soggetto a errori. E ci sono molti altri esempi là fuori. Ognuna di queste cose, in isolamento, può sembrare un inconveniente relativamente minore però, l'effetto complessivo è che ottenere vero lavoro fatto in MS SQL Server è molto più difficile e più soggetto a errori rispetto a PostgreSQL, e gli analisti di dati trascorrere del tempo prezioso ed energie sulle soluzioni ei processi manuali, invece di concentrarsi sul problema reale. Aggiornamento: è stato mi ha fatto notare che uno realmente utile funzione MS SQL Server dispone che PostgreSQL manca è la possibilità di dichiarare le variabili in script SQL. Come questo: PostgreSQL non posso fare questo. Vorrei che poteva, perché ci sono un sacco di usi per una tale funzione. 1.3. È possibile eseguire PostgreSQL in Linux, BSD, ecc (e, naturalmente, Windows) Chi segue gli sviluppi nel settore IT sa che cross-platform è una cosa ora. supporto cross-platform è senza dubbio la caratteristica killer di Java, che è in realtà un po 'grumoso, linguaggio di programmazione brutto, ma comunque un enorme successo, influente e diffuso. Microsoft non ha più il monopolio di una volta goduto sul desktop, grazie alla crescita di Linux e Apple. infrastrutture IT sono sempre più eterogenei grazie alla flessibilità dei servizi cloud e un facile accesso alla tecnologia di virtualizzazione ad alte prestazioni. software multipiattaforma è di dare all'utente il controllo sulla loro infrastruttura. (Al lavoro attualmente gestire diversi database PostgreSQL, alcuni in Windows e alcuni in Ubuntu Linux. Io ei miei colleghi muoversi liberamente codice e il database discariche tra di loro. Usiamo Python e PHP perché lavorano anche in entrambi i sistemi operativi. Tutto funziona .) la politica Microsofts è ed è sempre stata vendor lock-in. Essi non open-source il loro codice che non forniscono le versioni cross-platform del loro software hanno anche inventato un intero ecosistema. NET, progettato per disegnare una linea dura tra gli utenti di Microsoft e gli utenti non Microsoft. Questo è un bene per loro, perché salvaguarda le loro entrate. E 'un male per voi, l'utente, perché limita le scelte e crea lavoro inutile per voi. (Update: un paio di giorni dopo ho pubblicato questo, Microsoft mi ha fatto sembrare un Prat annunciando che era aperto-sourcing Quello è un grande passo, ma non lascia rompere aperto il Bollinger appena ancora.). Ora, questo non è un Linux vs Windows documento, anche se sono sicuro che Ill finiscono per scrivere uno di quelli ad un certo punto. Basti dire che, per il vero lavoro IT, Linux (e la famiglia UNIX-like: Solaris, BSD, ecc) lascia di Windows nella polvere. i sistemi operativi UNIX-like dominano il mercato dei server, i servizi cloud, supercomputing (in questo campo il suo un quasi monopolio) e calcolo tecnico, e con buona ragione ndash questi sistemi sono progettati da techies per techies. Come risultato si scambiano facilità d'uso per l'enorme potenza e flessibilità. Una corretta OS UNIX-like non è solo una riga di comando bella ndash è un ecosistema di programmi, programmi di utilità, funzionalità e supporto che fa ottenere reale lavoro svolto efficiente e piacevole. Un hacker Linux competente può raggiungere in una sola linea usa e getta di Bash script di un compito che sarebbe arduo e richiede molto tempo in Windows. (Esempio: l'altro giorno stavo guardando attraverso una collezione amici di film e lui ha detto che pensava che il numero totale di file nel file system è stato elevato, considerando come molti film che aveva, e si chiese se magari avesse accidentalmente copiato una cartella di grandi dimensioni . struttura in una delle sue cartelle di film che ho fatto un conteggio ricorsiva di file-per-cartella per lui in questo modo. Il tutto è durato circa un minuto per scrivere e un secondo per eseguirlo confermato che alcune delle sue cartelle avuto un problema e gli ha detto che quelli che erano. Come si dovrebbe fare questo in Windows) per l'analisi di dati, un RDBMS doesnt esiste in un vuoto che è parte di una pila strumento. Pertanto il suo ambiente conta. MS SQL Server è limitato a Windows, e Windows è semplicemente un ambiente povero di analisi. 1.4. linguaggio procedurale Caratteristiche Questo è un biggie. Pure SQL dichiarativa è bravo in quello che è stato progettato per ndash di manipolazione dei dati relazionali e l'interrogazione. Si raggiunge rapidamente i suoi limiti, se si tenta di utilizzare per processi analitici più coinvolti, come i calcoli di interesse complessi, analisi di serie temporali e disegno generale algoritmo. provider di database SQL lo sanno, così quasi tutti i database SQL implementano un certo tipo di linguaggio procedurale. Questo consente a un utente di database per scrivere codice imperativo stile per compiti più complessi o poco pratici. supporto per la lingua procedurale PostgreSQLs è eccezionale. La sua impossibile rendere giustizia ad esso in un breve spazio, ma heres un campione della merce. Uno qualsiasi di questi linguaggi procedurali possono essere utilizzati per la scrittura di stored procedure e funzioni o semplicemente scaricati in un blocco di codice da eseguire in linea. Plpgsql: questo è PostgreSQLs linguaggio procedurale nativa. E 'come oracoli PLSQL, ma più moderno e funzionalità complete. PLV8: il motore JavaScript V8 di Google Chrome è disponibile in PostgreSQL. Questo motore è stabile, ricco di funzionalità e assurdamente ndash veloce spesso si avvicina alla velocità di esecuzione dei compilato, ottimizzato C. Che si combinano con PostgreSQLs supporto nativo per il tipo di dati JSON (vedi sotto) e si ha il potere e flessibilità in un unico pacchetto. Ancora meglio, PLV8 supporta stato globale (cioè cross-funzione di chiamata), che permette all'utente di dati in modo selettivo della cache in RAM per accesso casuale veloce. Si supponga di dover usare 100.000 righe di dati da tabella A su ciascuna delle 1.000.000 righe di dati dalla tabella B. In SQL tradizionale, vi sia bisogno di unire queste tabelle (risultanti in una tabella intermedia 100 miliardi di fila, che uccidono qualsiasi ma il più immense server) or do something akin to a scalar subquery (or, worse, cursor-based nested loops), resulting in crippling IO load if the query planner doesnt read your intentions properly. In PLV8 you simply cache table A in memory and run a function on each of the rows of table B ndash in effect giving you RAM-quality access (negligible latency and random access penalty no non-volatile IO load) to the 100k-row table. I did this on a real piece of work recently ndash my PostgreSQLPLV8 code was about 80 times faster than the MS T-SQL solution and the code was much smaller and more maintainable. Because it took about 23 seconds instead of half an hour to run, I was able to run 20 run-test-modify cycles in an hour, resulting in feature-complete, properly tested, bug-free code. Look here for more detail on this. (All those run-test-modify cycles were only possible because of DROP SCHEMA CASCADE and freedom to execute CREATE FUNCTION statements in the middle of a statement batch, as explained above. See how nicely it all fits together) PLPython: you can use full Python in PostgreSQL. Python2 or Python 3, take your pick, and yes, you get the enormous ecosystem of libraries for which Python is justifiably famous. Fancy running a SVM from scikit-learn or some arbitrary-precision arithmetic provided by gmpy2 in the middle of a SQL query No problem PLPerl: Perl has been falling out of fashion for some time, but its versatility earned it a reputation as the Swiss army knife of programming languages. In PostgreSQL you have full Perl as a procedural language. PLR: R is the de facto standard statistical programming environment in academia and data science, and with good reason - it is free, robust, fully-featured and backed by an enormous library of high-quality plugins and add-ons. PostgreSQL lets you use R as a procedural language. Java, Lua, sh, Tcl, Ruby and PHP are also supported as procedural languages in PostgreSQL. C: doesnt quite belong in this list because you have to compile it separately, but its worth a mention. In PostgreSQL it is trivially easy to create functions which execute compiled, optimised C (or C or assembler) in the database backend. This is a power user feature which provides unrivalled speed and fine control of memory management and resource usage for tasks where performance is critical. I have used this to implement a complex, stateful payment processing algorithm operating on a million rows of data per second ndash and that was on a desktop PC. MS SQL Servers inbuilt procedural language (part of their T-SQL extension to SQL) is clunky, slow and feature-poor. It is also prone to subtle errors and bugs, as Microsofts own documentation sometimes acknowledges. I have never met a database user who likes the T-SQL procedural language. What about the fact that you can make assemblies in languages and then use them in MS SQL Server This doesnt count as procedural language support because you cant submit this code to the database engine directly. Manageability and ergonomics are critically important. Inserting some Python code inline in your database query is easy and convenient firing up Visual Studio, managing projects and throwing DLL files around (all in GUI-based processes which cannot be properly scripted, version-controlled, automated or reviewed) is awkward, error-prone and non-scalable. In any case, this mechanism is limited to languages. 1.5. Native regular expression support Regular expressons (regexen or regexes) are as fundamental to analytics work as arithmetic ndash they are the first choice (and often only choice) for a huge variety of text processing tasks. A data analytics tool without regex support is like a bicycle without a saddle ndash you can still use it, but its painful. PostgreSQL has smashing out-of-the-box support for regex. Some examples: Get all lines starting with a repeated digit followed by a vowel: Get the first isolated hex string occurring in a field: Break a string on whitespace and return each fragment in a separate row: Case-insensitively find all words in a string with at least 10 letters: MS SQL Server has LIKE. SUBSTRING. PATINDEX and so on, which are not comparable to proper regex support (if you doubt this, try implementing the above examples using them). There are third-party regex libraries for MS SQL Server theyre just not as good as PostgreSQLs support, and the need to obtain and install them separately adds admin overhead. Note also that PostgreSQLs extensive procedural language support also gets you several other regex engines and their various features - e. g. Pythons regex library provides the added power of positive and negative lookbehind assertions. This is in keeping with the general theme of PostgreSQL giving you all the tools you need to actually get things done. 1.6. Custom aggregate functions This is a feature that, technically, is offered by both PostgreSQL and MS SQL Server. The implementations differ hugely, though. In PostgreSQL, custom aggregates are convenient and simple to use, resulting in fast problem-solving and maintainable code: Elegant, eh A custom aggregate is specified in terms of an internal state and a way to modify that state when we push new values into the aggregate function. In this case we start each customer off with zero balance and no interest accrued, and on each day we accrue interest appropriately and account for payments and withdrawals. We compound the interest on the 1st of every month. Notice that the aggregate accepts an ORDER BY clause (since, unlike SUM. MAX and MIN. this aggregate is order-dependent) and PostgreSQL provides operators for extracting values from JSON objects. So, in 28 lines of code weve created the framework for monthly compounding interest on bank accounts and used it to calculate final balances. If features are to be added to the methodology (e. g. interest rate modifications depending on debitcredit balance, detection of exceptional circumstances), its all right there in the transition function and is written in an appropriate language for implementing complex logic. (Tragic side-note: I have seen large organisations spend tens of thousands of pounds over weeks of work trying to achieve the same thing using poorer tools.) MS SQL Server, on the other hand, makes it absurdly difficult . Incidentally, the examples in the second link are for implementing a simple string concatenation aggregate. Note the huge amount of code and gymnastics required to implement this simple function (which PostgreSQL provides out of the box, incidentally. Probably because its useful). MS SQL Server also does not allow an order to be specified in the aggregate, which renders this function useless for my kind of work ndash with MS SQL Server, the order of string concatenation is random, so the results of a query using this function are non-deterministic (they might change from run to run) and the code will not pass a quality review. The lack of ordering support also breaks code such as the interest calculation example above. As far as I can tell, you just cant do this using an MS SQL Server custom aggregate. (It is actually possible to make MS SQL Server do a deterministic string concatenation aggregation in pure SQL but you have to abuse the RECURSIVE query functionality to do it. Although an interesting academic exercise, this results in slow, unreadable, unmaintainable code and is not a real-world solution). 1.7. Unicode support Long gone are the days when ASCII was universal, character and byte were fungible terms and foreign (from an Anglocentric standpoint) text was an exotic exception. Proper international language support is no longer optional. The solution to all this is Unicode. There are a lot of misconceptions about Unicode out there. Its not a character set, its not a code page, its not a file format and its nothing whatsoever to do with encryption. An exploration of how Unicode works is fascinating but beyond the scope of this document ndash I heartily recommend Googling it and working through a few examples. The key points about Unicode that are relevant to database functionality are: Unicode-encoded text (for our purposes this means either UTF-8 or UTF-16) is a variable-width encoding. In UTF-8 a character can take one, two, three or four bytes to represent. In UTF-16 its either two or four. This means that operations like taking substrings and measuring string lengths need to be Unicode-aware to work properly. Not all sequences of bytes are valid Unicode. Manipulating valid Unicode without knowing its Unicode is likely to produce something that is not valid Unicode. UTF-8 and UTF-16 are not compatible. If you take one file of each type and concatenate them, you (probably) end up with a file which is neither valid UTF-8 nor valid UTF-16. For text which mostly fits into ASCII, UTF-8 is about twice as space-efficient as UTF-16. PostgreSQL supports UTF-8. Its CHAR. VARCHAR and TEXT types are, by default, UTF-8, meaning they will only accept UTF-8 data and all the transformations applied to them, from string concatenation and searching to regular expressions, are UTF-8-aware. It all just works. MS SQL Server 2008 does not support UTF-16 it supports UCS-2, a deprecated subset of UTF-16. What this means is that most of the time, it will look like its working fine, and occasionally, it will silently corrupt your data. Since it interprets text as a string of wide (i. e. 2-byte) characters, it will happily cut a 4-byte UTF-16 character in half. At best, this results in corrupted data. At worst, something else in your toolchain will break badly and youll have a disaster on your hands. Apologists for MS are quick to point out that this is unlikely because it would require the data to contain something outside Unicodes basic multilingual plane. This is completely missing the point. A databases sole purpose is storing, retreiving and manipulating data. A database which can be broken by putting the wrong data in it is as useless as a router that breaks if you download the wrong file. MS SQL Server versions since 2012 have supported UTF-16 properly, if you ensure you select a UTF-16-compliant collation for your database. It is baffling that this is (a) optional and (b) implemented as late as 2012. Better late than never, I suppose. 1.8. Data types that work properly A common misconception is that all databases have the same types ndash INT. CHAR. DATE and so on. Questo non è vero. PostgreSQLs type system is really useful and intuitive, free of annoyances which introduce bugs or slow work down and, as usual, apparently designed with productivity in mind. MS SQL Servers type system, by comparison, feels like beta software. It cant touch the feature set of PostgreSQLs type system and it is beset with traps waiting to ensnare the unwary user. Lets take a look: CHAR, VARCHAR and family PostgreSQL: the docs actively encourage you to simply use the TEXT type. This is a high-performance, UTF-8 validated text storage type which stores strings up to 1GB in size. It supports all the text operations PostgreSQL is capable of: simple concatenation and substringing regex searching, matching and splitting full-text search casting character transformation and so on. If you have text data, stick it in a TEXT field and carry on. Moreover, since anything in a TEXT field (or, for that matter, CHAR or VARCHAR fields) must be UTF-8, there is no issue with encoding incompatibility. Since UTF-8 is the de facto universal text encoding, converting text to it is easy and reliable. Since UTF-8 is a superset of ASCII, this conversion is often trivially easy or altogether unnecessary. It all just works. MS SQL Server: its a pretty sad story. The TEXT and NTEXT types exist and stretch to 2GB. Bafflingly, though, they dont support casting. Also, dont use them, says MS ndash they will be removed in a future version of MS SQL Server. You should use CHAR. VARCHAR and their N - prefixed versions instead. Unfortunately, VARCHAR(MAX) has poor performance characteristics and VARCHAR(8000) (the next biggest size, for some reason) tops out at 8,000 bytes. (Its 4,000 characters for NVARCHAR .) Remember how PostgreSQLs insistence on a single text encoding per database makes everything work smoothly Not so in MS-land: As with earlier versions of SQL Server, data loss during code page translations is not reported. link In other words, MS SQL Server might corrupt your data, and you wont know about it until something else goes wrong. This is, quite simply, a deal-breaker. A data analytics platform which might silently change, corrupt or lose your data is an enormous liability. Consider the absurdity of forking out for a server using expensive ECC RAM as a defence against data corruption caused by cosmic rays, and then running software on it which might corrupt your data anyway. Date and time types PostgreSQL: you get DATE. TIME. TIMESTAMP and TIMESTAMP WITH TIME ZONE. all of which do exactly what you would expect. They also have fantastic range and precision, supporting microsecond resolution from the 5th millennium BC to almost 300 millennia in the future. They accept input in a wide variety of formats and the last one has full support for time zones. They can be converted to and from Unix time, which is very important for interoperability with other systems. They can take the special values infinity and - infinity. This is not a metaphysico-theologico-philosophical statement, but a hugely useful semantic construction. For example, set a users password expiry date to infinity to denote that they do not have to change their password. The standard way of doing this is to use NULL or some date far in the future, but these are clumsy hacks ndash they both involve putting inaccurate information in the database and writing application logic to compensate. What happens when a developer sees NULL or 3499-12-31. 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. E così via. 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 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. Wow. 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 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.

No comments:

Post a Comment