• Stars
    star
    195
  • Rank 192,160 (Top 4 %)
  • Language
    JavaScript
  • Created about 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🐘 Learn how to use PostgreSQL and Structured Query Language (SQL) to store and query your relational data. πŸ”

Learn PostgreSQL

Learn how to use PostgreSQL and Structured Query Language (SQL) to store and query your data.



Build Status codecov.io Dependencies: None! devDependencies Status contributions welcome

Why?

Helping people store, retrieve and derive insights from data is the essence of all software applications.

SQL is Everywhere

Like it or not, Relational Databases store most of the world's structured data and Structured Query Language (SQL) is by far the most frequent way of retrieving the data.

According to the most recent surveys/statistics, SQL still dominates the world of databases.

https://insights.stackoverflow.com/survey/2018/#technology-databases stackoverflow-survey-2018-databases

https://db-engines.com/en/ranking dbms-ranking

Note: you should never adopt a technology based on it's current popularity, also be ware of "argumentum ad populum" ("it's popular therefore you should use it"). Always pick the appropriate tool for the job based on the requirements, constraints and/or availability (both of "skill" on your existing team or in the wider community). We include these stats to explain that relational databases are still the most widely used by far and so learning SQL skills is a very wise investment both as an individual and for your team or organisation.

PostgreSQL is Easy to Learn and it Runs Everywhere!

Getting started with PostgreSQL is easy, (just follow the steps in this guide and try out the example queries!)
When you are ready to deploy your app, you are in safe hands, PostgreSQL runs everywhere:

Who?

Everyone building any application that stores data should learn SQL. SQL is ubiquitous in every field/industry and the sooner you learn/master it, the higher your life-time return on time investment.

Learning how to use a relational database is a foundational skill for all of computer science and application development.

Being proficient in SQL will open the door to Data Science with SQL-on-Hadoop Apache Spark, Google BigQuery, Oracle and Teradata. In short, get really good at SQL! It's very useful.

What?

This tutorial covers 5 areas:

  1. What is PostgreSQL?
  2. How do I get started with PostgreSQL? (a fully functioning example!)
  3. What is Structured Query Language (SQL)? (lots of example queries!)
  4. How do I write my own SQL Queries?
  5. How do I deploy my own PostgreSQL-based Application?

Once you have covered these areas, you will know if PostgreSQL is "right" for your needs, or if you need to keep looking for a different way to store data.

Let's dive in!

1. What is PostgreSQL?

PostgreSQL (often shortened to simply "Postgres") is an advanced Relational DataBase Management System ("RDBMS"), that lets you efficiently and securely store any type of data. We will explain "Relational Database" in the context of our example below, so don't worry if it sounds like a buzzword soup.

Postgres has an emphasis on standards compliance and extensibility which means there are many plugins you can use to enhance it like PostGIS for mapping applications and entire projects built on top of it like TimescaleDB (a time-series database perfect for analytics) and AgensGraph (a graph database, great for modelling networks e.g a "social graph").

Structured Query Language (SQL) is the preferred means of interacting with data at any scale.

The only reason MySQL is still more widely used than Postgres can be summarised in one word: WordPress. WordPress has a firm grip on the CMS-based website market and it shows no sign of slowing down. If your goal is to build CMS-based websites, or the company you already work for uses WordPress, you should go for it! If you prefer a more general introduction to SQL, follow this tutorial! The knowledge you will gain by learning Postgres is 95%+ "transferable" to other SQL databases so don't worry about the differences between MySQL and Postgres for now. If you're curious, read: https://hackr.io/blog/postgresql-vs-mysql

How?

Installation

Before you get started with using PostgreSQL, you'll have to install it. Follow these steps to get started:

MacOS

  1. There are a couple of ways to install PostgreSQL. One of the easier ways to get started is with Postgres.app. Navigate to https://postgresapp.com/ and then click "Download": download

  2. Once it's finished downloading, double click on the file to unzip then move the PostgreSQL elephant icon into your applications folder. Double click the icon to launch the application.

  3. You should now see a new window launched with a list of servers to the left side of the window (if it's a fresh install, you should see one named PostgreSQL XX). If it shows anything else or an error props up, make sure you don't have any other instances of Postgres on your computer and reinstall. To fully reinstall follow these steps to delete data directories and preferences. Click on the button 'Initialize' (or 'Start' if you had already installed previously).

download

  1. Run sudo mkdir -p /etc/paths.d && echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp (found here) to use psql in the terminal. Close and open the terminal.

  2. Postgres.app will by default create a role and database that matches your current macOS username. You can connect straight away by running psql.

  3. You should then see something in your terminal that looks like this (with your macOS username in front of the prompt rather than 'postgres'):

terminal

  1. You should now be all set up to start using PostgreSQL. For documentation on command line tools etc see https://postgresapp.com/documentation/

Ubuntu

Digital Ocean have got a great article on getting started with postgres. A quick summary is below.

Installation
sudo apt-get update
sudo apt-get install postgresql postgresql-contrib

By default the only role created is the default 'postgres', so PostgreSQL will only respond to connections from an Ubuntu user called 'postgres'. We need to pretend to be that user and create a role matching our actual Ubuntu username:

sudo -u postgres createuser --interactive

This command means 'run the command createuser --interactive as the user called "postgres"'.

When asked for the name of the role enter your Ubuntu username. If you're not sure, open a new Terminal tab and run whoami.

When asked if you want to make the role a superuser, type 'y'.

We now need to create the database matching the role name, as PostgreSQL expects this. Run:

sudo -u postgres createdb [your user name]

You can now connect to PostgreSQL by running psql.

Create your first PostgreSQL database

  1. To start PostgreSQL, type this command into the terminal:
    psql

  2. Next type this command into the PostgreSQL interface:
    CREATE DATABASE test;
    NOTE: Don't forget the semi-colon. If you do, useful error messages won't show up.

  3. To check that our database has been created, type \l into the psql prompt. You should see something like this in your terminal: test db

Create new users for your database

  1. If you closed the PostgreSQL server, start it again with:
    psql

  2. To create a new user, type the following into the psql prompt:

    CREATE USER testuser;
  3. Check that your user has been created. Type \du into the prompt. You should see something like this: user Users can be given certain permissions to access any given database you have created.

  4. Next we need to give our user permissions to access the test database we created above. Enter the following command into the psql prompt:

    GRANT ALL PRIVILEGES ON DATABASE test TO testuser;

PostGIS - Spacial and Geographic objects for PostgreSQL

PostGIS Installation

If you've installed Postgres App as in the example above, you can easily extend it to include PostGIS. Follow these steps to begin using PostGIS:

  1. Ensure that you're logged in as a user OTHER THAN postgres. Follow the steps above to enable your default user to be able to access the psql prompt. (installation step 7)

  2. Type the following into the psql prompt to add the extension:
    CREATE EXTENSION postgis;

PostGIS Distance between two sets of coordinates

After you've extended PostgreSQL with PostGIS you can begin to use it. Type the following command into the psql command line:

SELECT ST_Distance(gg1, gg2) As spheroid_dist
FROM (SELECT
	ST_GeogFromText('SRID=4326;POINT(-72.1235 42.3521)') As gg1,
	ST_GeogFromText('SRID=4326;POINT(-72.1235 43.1111)') As gg2
	) As foo  ;

This should return spheroid_dist along with a value in meters. The example above returns: 84315.42034614 which is rougly 84.3km between the two points.

Commands

Once you are serving the database from your computer

  • To change db \connect database_name;

  • To see the tables in the database \d;

  • To select (and show in terminal) all tables SELECT * FROM table_name

  • To make a table CREATE TABLE table_name (col_name1, col_name2)

  • To add a row INSERT INTO table_name ( col_name ) VALUES ( col_value) col_name only require if only some of the cols are being filled out

  • To edit a column to a tableΒ  ALTER TABLE table_name Β  ALTER COLUMN column_name SET DEFAULT expression

  • To add a column to a tableΒ  ALTER TABLE table_name Β  ADD COLUMN column_name data_type

  • To find the number of instances where the word β€œDay” is present in the title of a table SELECT count(title) FROM table_name WHERE title LIKE '%Day%’;

  • To delete a row in a table DELETE FROM table_name WHERE column_name = β€˜hello';

Postgresql follows the SQL convention of calling relations TABLES, attributes COLUMNs and tuples ROWS

Transaction All or nothing, if something fails the other commands are rolled back like nothing happened

Reference When a table is being created you can reference a column in another table to make sure any value which is added to that column exists in the referenced table.

CREATE TABLE cities (
  name text NOT NULL,
  postal_code varchar(9) CHECK (postal_code <> ''),
  country_code char(2) REFERENCES countries,
  PRIMARY KEY (country_code, postal_code)
);

<> means not equal

Join reads You can join tables together when reading them,

Inner Join Joins together two tables by specifying a column in each to join them by i.e.

SELECT cities.*, country_name
  FROM cities INNER JOIN countries
  ON cities.country_code = countries.country_code;

This will select all of the columns in both the countries and cities tables the data, the rows are matched up by country_code.

Grouping You can put rows into groups where the group is defined by a shared value in a particular column.

SELECT venue_id, count(*)
  FROM events
  GROUP BY venue_id;

This will group the rows together by the venue_id, count is then performed on each of the groups.

Learning Resources

More Repositories

1

english-words

πŸ“ A text file containing 479k English words for all your dictionary/word-based projects e.g: auto-completion / autosuggestion
Python
9,337
star
2

learn-json-web-tokens

πŸ” Learn how to use JSON Web Token (JWT) to secure your next Web App! (Tutorial/Example with Tests!!)
JavaScript
4,178
star
3

learn-to-send-email-via-google-script-html-no-server

πŸ“§ An Example of using an HTML form (e.g: "Contact Us" on a website) to send Email without a Backend Server (using a Google Script) perfect for static websites that need to collect data.
HTML
3,047
star
4

repo-badges

⭐ Use repo badges (build passing, coverage, etc) in your readme/markdown file to signal code quality in a project.
HTML
2,831
star
5

learn-tdd

βœ… A brief introduction to Test Driven Development (TDD) in JavaScript (Complete Beginner's Step-by-Step Tutorial)
JavaScript
2,698
star
6

start-here

πŸ’‘ A Quick-start Guide for People who want to dwyl ❀️ βœ…
1,725
star
7

learn-elixir

πŸ’§ Learn the Elixir programming language to build functional, fast, scalable and maintainable web applications!
Elixir
1,586
star
8

learn-travis

😎 A quick Travis CI (Continuous Integration) Tutorial for Node.js developers
JavaScript
1,251
star
9

Javascript-the-Good-Parts-notes

πŸ“– Notes on the seminal "JavaScript the Good Parts: by Douglas Crockford
1,173
star
10

aws-sdk-mock

🌈 AWSomocks for Javascript/Node.js aws-sdk tested, documented & maintained. Contributions welcome!
JavaScript
1,079
star
11

learn-aws-lambda

✨ Learn how to use AWS Lambda to easily create infinitely scalable web services
JavaScript
1,035
star
12

book

πŸ“— Our Book on Full-Stack Web Application Development covering User Experience (UX) Design, Mobile/Offline/Security First, Progressive Enhancement, Continuous Integration/Deployment, Testing (UX/TDD/BDD), Performance-Driven-Development and much more!
Rust
816
star
13

hapi-auth-jwt2

πŸ”’ Secure Hapi.js authentication plugin using JSON Web Tokens (JWT) in Headers, URL or Cookies
JavaScript
795
star
14

learn-hapi

β˜€οΈ Learn to use Hapi.js (Node.js) web framework to build scalable apps in less time
HTML
794
star
15

phoenix-chat-example

πŸ’¬ The Step-by-Step Beginners Tutorial for Building, Testing & Deploying a Chat app in Phoenix 1.7 [Latest] πŸš€
Elixir
721
star
16

learn-tachyons

😍 Learn how to use Tachyons to craft beautiful, responsive and fast UI with functional CSS!
HTML
670
star
17

learn-phoenix-framework

πŸ”₯ Phoenix is the web framework without compromise on speed, reliability or maintainability! Don't settle for less. πŸš€
Elixir
639
star
18

learn-nightwatch

🌜 Learn how to use Nightwatch.js to easily & automatically test your web apps in *real* web browsers.
JavaScript
585
star
19

javascript-todo-list-tutorial

βœ… A step-by-step complete beginner example/tutorial for building a Todo List App (TodoMVC) from scratch in JavaScript following Test Driven Development (TDD) best practice. 🌱
JavaScript
532
star
20

learn-elm

🌈 discover the beautiful programming language that makes front-end web apps a joy to build and maintain!
HTML
472
star
21

learn-redux

πŸ’₯ Comprehensive Notes for Learning (how to use) Redux to manage state in your Web/Mobile (React.js) Apps.
HTML
446
star
22

learn-devops

🚧 Learn the craft of "DevOps" (Developer Operations) to Deploy your App and Monitor it so it stays "Up"!
Shell
411
star
23

hits

πŸ“ˆ General purpose hits (page views) counter
Elixir
397
star
24

hapi-socketio-redis-chat-example

πŸ’¬ Real-time Chat using Hapi.js + Socket.io + Redis Pub/Sub (example with tests!!)
Elm
363
star
25

hapi-typescript-example

⚑ Hapi.Js + Typescript = Awesomeness
TypeScript
351
star
26

phoenix-liveview-counter-tutorial

🀯 beginners tutorial building a real time counter in Phoenix 1.7.7 + LiveView 0.19 ⚑️ Learn the fundamentals from first principals so you can make something amazing! πŸš€
Elixir
345
star
27

learn-istanbul

🏁 Learn how to use the Istanbul JavaScript Code Coverage Tool
JavaScript
339
star
28

learn-redis

πŸ“• Need to store/access your data as fast as possible? Learn Redis! Beginners Tutorial using Node.js πŸš€
JavaScript
291
star
29

technology-stack

πŸš€ Detailed description + diagram of the Open Source Technology Stack we use for dwyl projects.
JavaScript
281
star
30

phoenix-ecto-encryption-example

πŸ” A detailed example for how to encrypt data in an Elixir (Phoenix v1.7) App before inserting into a database using Ecto Types
Elixir
269
star
31

learn-elasticsearch

πŸ” Learn how to use ElasticSearch to power a great search experience for your project/product/website.
Elixir
265
star
32

home

🏑 πŸ‘©β€πŸ’» πŸ’‘ home is where you can [learn to] build the future surrounded by like-minded creative, friendly and [intrinsically] motivated people focussed on health, fitness and making things people and the world need!
244
star
33

elixir-auth-google

πŸ‘€Minimalist Google OAuth Authentication for Elixir Apps. Tested, Documented & Maintained. Setup in 5 mins. πŸš€
Elixir
228
star
34

learn-docker

🚒 Learn how to use docker.io containers to consistently deploy your apps on any infrastructure.
Dockerfile
220
star
35

learn-elm-architecture-in-javascript

πŸ¦„ Learn how to build web apps using the Elm Architecture in "vanilla" JavaScript (step-by-step TDD tutorial)!
JavaScript
206
star
36

learn-environment-variables

πŸ“Learn how to use Environment Variables to keep your passwords and API keys secret. πŸ”
JavaScript
201
star
37

learn-tape

βœ… Learn how to use Tape for JavaScript/Node.js Test Driven Development (TDD) - Ten-Minute Testing Tutorial
JavaScript
185
star
38

sendemail

πŸ’Œ Simplifies reliably sending emails from your node.js apps using AWS Simple Email Service (SES)
JavaScript
181
star
39

phoenix-todo-list-tutorial

βœ… Complete beginners tutorial building a todo list from scratch in Phoenix 1.7 (latest)
Elixir
171
star
40

decache

:shipit: Delete Cached node_modules useful when you need to "un-require" during testing for a fresh state.
JavaScript
151
star
41

quotes

πŸ’¬ a curated list of quotes that inspire action + code that returns quotes by tag/author/etc. πŸ’‘
Elixir
150
star
42

learn-heroku

🏁 Learn how to deploy your web application to Heroku from scratch step-by-step in 7 minutes!
Python
149
star
43

learn-chrome-extensions

🌐 Discover how to build and deploy a Google Chrome Extension for your Project!
139
star
44

labels

🏷 Sync GitHub Labels from any Source to Target Repositories for Consistency across all your projects!
Elixir
136
star
45

ISO-27001-2013-information-technology-security

πŸ” Probably the most boring-but-necessary repo on GitHub. If you care about the security/privacy of your data...! βœ…
136
star
46

learn-ab-and-multivariate-testing

πŸ†Ž Tutorial on A/B and multivariate testing βœ”οΈ
135
star
47

web-form-to-google-sheet

A simple example of sending data from an ordinary web form straight to a Google Spreadsheet without a server.
HTML
133
star
48

app

Clear your mind. Organise your life. Ignore distractions. Focus on what matters.
Dart
133
star
49

auth

πŸšͺ πŸ” UX-focussed Turnkey Authentication Solution for Web Apps/APIs (Documented, Tested & Maintained)
Elixir
124
star
50

learn-circleci

βœ… A quick intro to Circle CI (Continuous Integration) for JavaScript developers.
121
star
51

learn-regex

⁉️ A simple REGular EXpression tutorial in JavaScript
120
star
52

learn-react

"The possibilities are numerous once we decide to act and not react." ~ George Bernard Shaw
HTML
108
star
53

learn-aws-iot

πŸ’‘ Learn how to use Amazon Web Services Internet of Things (IoT) service to build connected applications.
JavaScript
101
star
54

env2

πŸ’» Simple environment variable (from config file) loader for your node.js app
JavaScript
100
star
55

phoenix-liveview-chat-example

πŸ’¬ Step-by-step tutorial creates a Chat App using Phoenix LiveView including Presence, Authentication and Style with Tailwind CSS
Elixir
98
star
56

how-to-choose-a-database

How to choose the right dabase
93
star
57

imgup

πŸŒ… Effortless image uploads to AWS S3 with automatic resizing including REST API.
Elixir
88
star
58

contributing

πŸ“‹ Guidelines & Workflow for people contributing to our project(s) on GitHub. Please ⭐ to confirm you've read & understood! βœ…
85
star
59

javascript-best-practice

A collection of JavaScript Best Practices
83
star
60

learn-amazon-web-services

⭐ Amazing Guide to using Amazon Web Services (AWS)! ☁️
83
star
61

range-touch

πŸ“± Use HTML5 range input on touch devices (iPhone, iPad & Android) without bloatware!
JavaScript
83
star
62

learn-pre-commit

βœ… Pre-commit hooks let you run checks before allowing a commit (e.g. JSLint or check Test Coverage).
JavaScript
80
star
63

product-owner-guide

πŸš€ A rough guide for people working with dwyl as Product Owners
78
star
64

phoenix-ecto-append-only-log-example

πŸ“ A step-by-step example/tutorial showing how to build a Phoenix (Elixir) App where all data is immutable (append only). Precursor to Blockchain, IPFS or Solid!
Elixir
78
star
65

mvp

πŸ“² simplest version of the @dwyl app
Elixir
78
star
66

goodparts

πŸ™ˆ An ESLint Style that only allows JavaScript the Good Parts (and "Better Parts") in your code.
JavaScript
77
star
67

hapi-error

β˜” Intercept errors in your Hapi Web App/API and send a *useful* message to the client OR redirect to the desired endpoint.
JavaScript
76
star
68

flutter-todo-list-tutorial

βœ… A detailed example/tutorial building a cross-platform Todo List App using Flutter πŸ¦‹
Dart
75
star
69

process-handbook

πŸ“— Contains our processes, questions and journey to creating a team
HTML
75
star
70

dev-setup

✈️ A quick-start guide for new engineers on how to set up their Dev environment
73
star
71

aws-lambda-deploy

☁️ πŸš€ Effortlessly deploy Amazon Web Services Lambda function(s) with a single command. Less to configure. Latest AWS SDK and Node.js v20!
JavaScript
72
star
72

terminate

♻️ Terminate a Node.js Process (and all Child Processes) based on the Process ID
JavaScript
71
star
73

fields

🌻 fields is a collection of useful field definitions (Custom Ecto Types) that helps you easily define an Ecto Schema with validation, encryption and hashing functions so that you can ship your Elixir/Phoenix App much faster!
Elixir
69
star
74

learn-flutter

πŸ¦‹ Learn how to use Flutter to Build Cross-platform Native Mobile Apps
JavaScript
69
star
75

hapi-login-example-postgres

🐰 A simple registration + login form example using hapi-register, hapi-login & hapi-auth-jwt2 with a PostgreSQL DB
JavaScript
69
star
76

phoenix-liveview-todo-list-tutorial

βœ… Beginners tutorial building a Realtime Todo List in Phoenix 1.6.10 + LiveView 0.17.10 ⚑️ Feedback very welcome!
Elixir
64
star
77

learn-security

πŸ” For most technology projects Security is an "after thought", it does not have to be that way; let's be proactive!
64
star
78

learn-javascript

A Series of Simple Steps in JavaScript :-)
HTML
63
star
79

chat

πŸ’¬ Probably the fastest, most reliable/scalable chat system on the internet.
Elixir
62
star
80

learn-jsdoc

πŸ“˜ Use JSDoc and a few carefully crafted comments to document your JavaScript code!
CSS
60
star
81

ampl

πŸ“± ⚑ Ampl transforms Markdown into AMP-compliant html so it loads super-fast!
JavaScript
57
star
82

aguid

❄️ A Globally Unique IDentifier (GUID) generator in JS. (deterministic or random - you chose!)
JavaScript
56
star
83

tudo

βœ… Want to see where you could help on an open dwyl issue?
Elixir
56
star
84

learn-apple-watch-development

πŸ“— Learn how to build Native Apple Watch (+iPhone) apps from scratch!
Swift
55
star
85

learn-qunit

βœ… A quick introduction to JavaScript unit testing with QUnit
JavaScript
51
star
86

learn-ngrok

☁️ Learn how to use ngrok to share access to a Web App/Site running on your "localhost" with the world!
HTML
50
star
87

hapi-auth-jwt2-example

πŸ”’ A functional example Hapi.js app using hapi-auth-jwt2 & Redis (hosted on Heroku) with tests!
JavaScript
49
star
88

learn-jshint

πŸ’© Learn how to use the ~~jshint~~ code quality/consistency tool.
JavaScript
49
star
89

tachyons-bootstrap

πŸ‘’Bootstrap recreated using tachyons functional css
HTML
49
star
90

esta

πŸ” Simple + Fast ElasticSearch Node.js client. Beginner-friendly defaults & Heroku support βœ… πŸš€
JavaScript
48
star
91

learn-node-js-by-example

☁️ Practical node.js examples.
HTML
47
star
92

redis-connection

⚑ Single Redis Connection that can be used anywhere in your node.js app and closed once (e.g in tests)
JavaScript
45
star
93

product-roadmap

🌐 Because why wouldn't you make your company's product roadmap Public on GitHub?
45
star
94

aws-lambda-test-utils

Mock event and context objects without fluff.
JavaScript
44
star
95

learn-graphQL

❓Learn to use GraphQL - A query language that allows client applications to specify their data fetching requirements
JavaScript
44
star
96

elixir-pre-commit

βœ… Pre-commit hooks for Elixir projects
Elixir
43
star
97

hapi-login

πŸšͺ The Simplest Possible (Email + Password) Login for Hapi.js Apps βœ…
JavaScript
43
star
98

learn-riot

🐎 Riot.js lets you build apps that are simpler and load/run faster than any other JS framework/library.
HTML
43
star
99

github-reference

⭐ GitHub reference for *non-technical* people following a project's progress
42
star
100

learn-codeclimate

🌈 Learn how to use CodeClimate to track the quality of your JavaScript/Node.js code.
41
star