DigitalOcean Kubernetes: new control plane is faster and free, enable HA for 99.95% uptime SLA --> Tutorials Questions Tech Talks Get Involved Product Docs Products Pricing Docs Sign in search community Sign Up / // Tutorial // How To Install and Use PostgreSQL on Ubuntu 18.04 Published on May 5, 2018 · Updated on March 18, 2022 Databases Ubuntu Interactive PostgreSQL Ubuntu 18.04 By Justin Ellingwood and Mark Drake Not using Ubuntu 18.04? Choose a different version or distribution. Introduction CONTENTS Introduction Prerequisites Step 1 — Installing PostgreSQL Step 2 — Using PostgreSQL Roles and Databases Switching Over to the postgres Account Accessing a Postgres Prompt Without Switching Accounts Step 3 — Creating a New Role Step 4 — Creating a New Database Step 5 — Opening a Postgres Prompt with the New Role Step 6 — Creating and Deleting Tables Step 7 — Adding, Querying, and Deleting Data in a Table Step 8 — Adding and Relational database management systems are a key component of many web sites and applications. T organize, and access information. PostgreSQL, or Postgres, is a relational database management system that provides an implementatio popular choice for many small and large projects and has the advantage of being standards-compliant like reliable transactions and concurrency without read locks. This guide demonstrates how to install Postgres on an Ubuntu 18.04 VPS instance and also provides in administration. Prerequisites To follow along with this tutorial, you will need one Ubuntu 18.04 server that has been configured by fo Ubuntu 18.04 guide. After completing this prerequisite tutorial, your server should have a non-root use firewall. You can also use an interactive terminal that is embedded on this page to experiment with installing an tutorial. Click the following Launch an Interactive Terminal! button to get started. Launch an Interactive Terminal! Step 1 — Installing PostgreSQL Ubuntu’s default repositories contain Postgres packages, so you can install these using the apt packa Since this is your first time using apt in this session, refresh your local package index. Then, install th contrib package that adds some additional utilities and functionality: $ sudo apt update p g Deleting Columns from a Table Step 9 — Updating Data in a Table Conclusion R E L AT E D Initial Server Setup with Ubuntu 12.04 Tutorial How To Install Ruby on Rails on Ubuntu 12.04 LTS (Precise Pangolin) with RVM Tutorial $ sudo apt install postgresql postgresql-contrib Ensure that the server is running using the systemctl start command: $ sudo systemctl start postgresql.service Now that the software is installed and running, we can go over how it works and how it may be differe systems you may have used. Step 2 — Using PostgreSQL Roles and Databases By default, Postgres uses a concept known as roles to handle authentication and authorization. These Unix-style accounts, but Postgres does not distinguish between users and groups and instead prefers Upon installation, Postgres is set up to use ident authentication, meaning that it associates Postgres r account. If a role exists within Postgres, a Unix/Linux username with the same name is able to sign in a The installation procedure created a user account called postgres that is associated with the default P you can log into that account. There are a few ways to use this account to access Postgres. Switching Over to the postgres Account Switch over to the postgres account on your server by typing: $ sudo -i -u postgres You can now access a Postgres prompt immediately by typing: $ psql This will log you into the PostgreSQL prompt, and from here you are free to interact with the database Exit out of the PostgreSQL prompt by typing: postgres=# \q This will bring you back to the postgres Linux command prompt. Accessing a Postgres Prompt Without Switching Accounts In the last example, you were instructed to get to the Postgres prompt by first switching to the postgr the Postgres prompt. You could alternatively do this in one step by running the single command psql this: $ sudo -u postgres psql This will log you directly into Postgres without the intermediary bash shell in between. Again, you can exit the interactive Postgres session by typing: postgres=# \q Many use cases require more than one Postgres role. Read on to learn how to configure these. Step 3 — Creating a New Role Currently, you just have the postgres role configured within the database. You can create new roles fr createrole command. The --interactive flag will prompt you for the name of the new role and also permissions. If you are logged in as the postgres account, you can create a new user by typing: postgres@server:~$ createuser --interactive If, instead, you prefer to use sudo for each command without switching from your normal account, typ $ sudo -u postgres createuser --interactive The script will prompt you with some choices and, based on your responses, execute the correct Post meets your specifications. First, the prompt will ask you to specify a name for the new role. The following example names the role whatever you like: Output Enter name of role to add: sammy Next, you’ll be asked if the new role should be a superuser. In PostgreSQL, a superuser role has extrem bypass nearly all permission checks. The following example specifies that the sammy role should be a superuser but, because superuser ro control over a database, you should not grant new roles superuser status lightly: Output Enter name of role to add: sammy Shall the new role be a superuser? (y/n) y Note that you can only create new superuser roles if you are creating them as a role that is already a s is a superuser. You can get more control by passing some additional flags. Check out the options by looking at the ma $ man createuser Your installation of Postgres now has a new role, but you have not yet added any databases. The next Step 4 — Creating a New Database Another assumption that the Postgres authentication system makes by default is that for any role used with the same name which it can access. This means that, if the user you created in the last section is called sammy, that role will attempt to co “sammy” by default. You can create the appropriate database with the createdb command. If you are logged in as the postgres account, you would type something like: postgres@server:~$ createdb sammy If, instead, you prefer to use sudo for each command without switching from your normal account, you $ sudo -u postgres createdb sammy This flexibility provides multiple paths for creating databases as needed. Step 5 — Opening a Postgres Prompt with the New Role To log in with ident based authentication, you’ll need a Linux user with the same name as your Postg If you don’t have a matching Linux user available, you can create one with the adduser command. You account with sudo privileges (meaning, not logged in as the postgres user): $ sudo adduser sammy Once this new account is available, you can either switch over and connect to the database by typing $ sudo -i -u sammy $ psql Or, you can do this inline: $ sudo -u sammy psql This command will log you in automatically, assuming that all of the components have been properly c If you want your user to connect to a different database, you can do so by specifying the database like $ psql -d postgres Once logged in, you can get check your current connection information by typing: sammy=# \conninfo Output You are connected to database "sammy" as user "sammy" via socket in "/var/run/postgresql" This is useful if you are connecting to non-default databases or with non-default users. Step 6 — Creating and Deleting Tables Now that you know how to connect to the PostgreSQL database system, you can learn some basic Po First, create a table to store some data. As an example, a table that describes some playground equip The basic syntax for this command is as follows: CREATE TABLE table_name ( column_name1 col_type ( field_length ) column_constraints , column_name2 col_type ( field_length ), column_name3 col_type ( field_length ) ); These commands give the table a name, and then define the columns as well as the column type and also optionally add table constraints for each column. You can learn more about how to create and manage tables in Postgres here. For demonstration purposes, create a sample table like this: sammy=# CREATE TABLE playground ( sammy=# equip_id serial PRIMARY KEY, sammy=# type varchar (50) NOT NULL, sammy=# color varchar (25) NOT NULL, sammy=# location varchar(25) check (location in ('north', 'south', 'west', 'east', 'n sammy=# install_date date sammy=# ); These commands will create a table that inventories playground equipment. This starts with an equipm This data type is an auto-incrementing integer. You’ve also given this column the constraint of primar be unique and not null. For two of the columns ( equip_id and install_date ), the commands do not specify a field length. Th require a set length because the length is implied by the type. The next two commands create columns for the equipment type and color respectively, each of whi NOT NULL constraint applied to each). The line after these creates a location column and adds a con be one of eight possible values. The last line within the parentheses creates a date column that recor equipment. Note that in SQL, every statement must end in a semicolon ( ; ). If you entered the CREATE TABLE operation correctly, it will return this output: Output CREATE TABLE You can find a list of tables within this database by typing: sammy=# \d Output List of relations Schema | Name | Type | Owner --------+-------------------------+----------+------public | playground | table | sammy public | playground_equip_id_seq | sequence | sammy (2 rows) Your playground table is here, but there’s also something called playground_equip_id_seq that is of th representation of the serial type which you gave your equip_id column. This keeps track of the nex automatically for columns of this type. If you only want the table returned without the sequence, you can type: sammy=# \dt Output List of relations Schema | Name | Type | Owner --------+------------+-------+------public | playground | table | sammy (1 row) Step 7 — Adding, Querying, and Deleting Data in a Table Now that you have a table, you can insert some data into it. As an example, add a slide and a swing by calling the table you want to add to, naming the columns an like this: sammy=# INSERT INTO playground (type, color, location, install_date) VALUES ('slide', 'bl sammy=# INSERT INTO playground (type, color, location, install_date) VALUES ('swing', 'ye You should take care when entering the data to avoid a few common hangups. For one, do not wrap th but the column values that you enter do need quotes. Another thing to keep in mind is that you do not enter a value for the equip_id column. This is becaus whenever a new row in the table is created. Retrieve the information you’ve added by typing: sammy=# SELECT * FROM playground; Output equip_id | type | color | location | install_date ----------+-------+--------+-----------+-------------1 | slide | blue | south | 2017-04-28 2 | swing | yellow | northwest | 2018-08-16 (2 rows) This output indicates that your equip_id has been filled in successfully and that all of your other data If the slide on the playground breaks and you have to remove it, you can also remove the row from you sammy=# DELETE FROM playground WHERE type = 'slide'; Query the table again: sammy=# SELECT * FROM playground; Output equip_id | type | color | location | install_date ----------+-------+--------+-----------+-------------2 | swing | yellow | northwest | 2018-08-16 (1 row) Notice that your slide is no longer a part of the table. Step 8 — Adding and Deleting Columns from a Table After creating a table, you can modify it to add or remove columns relatively easily. Add a column to sh piece of equipment by typing: sammy=# ALTER TABLE playground ADD last_maint date; The next time you view your table information again, the new column will have been added (but no da sammy=# SELECT * FROM playground; Output equip_id | type | color | location | install_date | last_maint ----------+-------+--------+-----------+--------------+-----------2 | swing | yellow | northwest | 2018-08-16 | (1 row) To delete a column, you can enter an SQL statement very similar to the one you used to add the last_ work crew uses a separate tool to keep track of maintenance history, you can delete of the column by sammy=# ALTER TABLE playground DROP last_maint; This deletes the last_maint column and any values found within it, but leaves all the other data intact Step 9 — Updating Data in a Table So far, you’ve learned how to add records to a table and how to delete them, but this tutorial hasn’t ye entries. You can update the values of an existing entry by querying for the record you want and setting the co can query for the “swing” record (this will match every swing in your table) and change its color to “red swing set a paint job: sammy=# UPDATE playground SET color = 'red' WHERE type = 'swing'; You can verify that the operation was successful by querying the data again: sammy=# SELECT * FROM playground; Output equip_id | type | color | location | install_date ----------+-------+-------+-----------+-------------2 | swing | red | northwest | 2010-08-16 (1 row) As this output indicates, your slide is now registered as being red. Conclusion You are now set up with PostgreSQL on your Ubuntu 18.04 server. However, there is still much more to more guides that cover how to use Postgres: A comparison of relational database management systems Learn how to create and manage tables with Postgres Get better at managing roles and permissions Craft queries with Postgres with Select Learn how to secure PostgreSQL Learn how to backup a Postgres database Want to learn more? Join the DigitalOcean Community! Join our DigitalOcean community of over a million developers for free! Get help and share knowledg section, find tutorials and tools that will help you grow as a developer and scale your project or bus interest. Sign up -> About the authors Justin Ellingwood Author Developer and author at DigitalOcean. Mark Drake Author Manager, Developer Education Technical Writer @ DigitalOcean Still looking for an answer? Ask a question Was this helpful? Yes Sear No Comments 10 Comments H1 H2 H3 1. “ ” Leave a comment... Login to Comment avidican92 • December 16, 2018 After this line sudo adduser sammy it ask me for Postgres password. What password is expected? A “Sorry try again” and after three attends it says sudo: 3 incorrect password attempts Reply grandterr • September 2, 2019 In psql change the password: ALTER USER postgres WITH PASSWORD 'password'; Reply Widoyo • December 28, 2018 It’s should be Ubuntu user password (sudoer), Not postgres password Reply madrianhorning • June 30, 2020 Step 5 is very hard to understand. I don’t understand if I am supposed to be in my linux user or postg I’m trying to login with my adrian role psql -d postgres -U adrian but I get “Peer authentication failed for user adrian” This article had what I needed: https://www.digitalocean.com/community/tutorials/how-to-use-roles in-postgresql-on-a-vps--2 Reply Tom Nguyen • June 9, 2021 The article is very useful. Thank you. Reply enjoypb • August 18, 2019 Hey guys. This tutorial does not describe how to add postgres user to the sudoers file. It seems it sh ‘Accessing a Postgres Prompt Without Switching Accounts’ section as I was unable to do this step o Reply sihanoukstudy • March 7, 2019 I don’t know my postgresql password install i can not connection it Reply RegalarTech • October 26, 2018 @mdrake Thanks for the detailed step by step guide, I hope it will help many and really appreciate th efforts for requests. cheers. Reply RegalarTech • July 30, 2018 Hello guys can you add how to set up the postgres to allow authorized user to connect from postgre inshort allow remote access. because once we have access then its easy to manage database . then cmds . also we can directly connect our apps Reply Mark Drake • August 3, 2018 Hello @RegalarTech, thank you so much for your comment. We really appreciate your suggestion f are currently scoping out how we can best execute it. We’ll keep you posted! Reply nasowah • October 26, 2018 Hello @mdrake, Thanks for the tutorial. I will like to find out if there is an update on @RegalarTech’s request pls. Br, Stephen Reply Mark Drake • October 26, 2018 Hi @nasowah, and hello again @RegalarTech! We recently published this guide on How To Ins pgAdmin 4 in Server Mode. If you have any thoughts or suggestions for that guide, please sha comments section of that tutorial. Reply LittleTealDinghy • May 11, 2022 Hi Digital Ocean Team, I am trying to create a scripted installation of Postgres on Ubuntu 18.04.06, using bash. In order to d your post above as a starting point. The account that I am using is a sudoer on the machine. I am running the following two lines - the pr sudo apt-get -y update sudo apt-get -y install postgresql The apt update completes successfully, then the postgresql install chugs along until it reaches this p Selecting previously unselected package postgresql. Preparing to unpack …/postgresql_14+238.pgd postgresql (14+238.pgdg18.04+1) … Setting up postgresql-client-common (238.pgdg18.04+1) … Set (238.pgdg18.04+1) … Password: I have tried entering the password to my sudoer account - all it does is hang. I have also tried just hi I can see from your post and the /etc/passwd file that the Postgres install process creates a postgre the Password: prompt is asking for the password to this postgres account, I don’t know where to fin To summarize: Can this Password: prompt be avoided entirely? If the prompt can’t be avoided, where do I find the correct password? Thanks ! Reply kazungu61 • August 25, 2021 Great article. Useful article. Thank you. Reply rootofshiva • March 27, 2021 make it $ sudo apt-get install postgresql postgresql-contrib libpq-dev Reply surajyadav90388 • June 11, 2020 Thank you for this amazing article. I was always wonder why my “$psql” commands don’t work(due some other stuff like best way to create new user and databases etc. Precise, to the point and in-depth article. Gonna recommend everyone. Reply Load More Comments This work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 GET OUR BIWEEKLY NEWSLETTER Sign up for Infrastructure as a Newsletter. HOLLIE'S HUB FOR GOOD Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help. BECOME A CONTRIBUTOR You get paid; we donate to tech nonprofits. Featured on Community Kubernetes Course Learn Python 3 Machine Learning in Python Getting started with Go Intro to Kubernetes DigitalOcean Products Virtual Machines Managed Databases Managed Kubernetes Block Storage Object Storage Marketplace VPC Load Balancers Welcome to the developer cloud DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether you’re running one virtual machine or ten thousand. Learn More Company Products Community Solutions Contact About Leadership Blog Careers Customers Partners Referral Program Press Legal Trust Platform Investor Relations DO Impact Products Overview Droplets Kubernetes App Platform Functions Managed Databases Spaces Marketplace Load Balancers Block Storage Tools & Integrations API Pricing Documentation Release Notes Tutorials Meetups Q&A CSS-Tricks Write for DOnations Droplets for Demos Hatch Startup Program Shop Swag Research Program Currents Research Open Source Code of Conduct Newsletter Signup Web & Mobile Apps Website Hosting Game Development Streaming VPN Startups SaaS Solutions Agency & Web Dev Shops Managed Cloud Hosting Providers Big Data Business Solutions Cloud Hosting for Blockchain Support Sales Report Abuse System Status Share your ideas © 2022 DigitalOcean, LLC. All rights reserved.