Anda di halaman 1dari 159

Contents

Azure DB for PostgreSQL Docs


Overview
Azure DB for PostgreSQL
Quickstarts
Create DB - Portal
Create DB - Azure CLI
Connect & query
Python
Node.js
Java
Ruby
PHP
.NET
Go
Tutorials
1 - Design a Database
Azure portal
Azure CLI
2 - Design Web App - Python
Samples
Azure CLI
Concepts
DB & Servers
Servers
Supported versions
PostgreSQL extensions
Server logs
High availability
Resources
Pricing tiers
Limits
Data access & security
Firewall rules
Configure SSL
VNet
Business continuity
Overview
Backup and restore
Monitor
Development
Connection libraries
How-to guides
Create users
Manage firewall
Azure portal
Azure CLI
Restore a server
Azure portal
Azure CLI
Migrate a database
Dump & restore
Import & export
Minimal-downtime migration
Configure server parameters
Azure portal
Azure CLI
Access server logs
Azure portal
Azure CLI
Monitor
Create alerts on metrics
Virtual Network
Azure portal
Azure CLI
Reference
Azure CLI
REST API
Resources
Deployment templates
Azure Roadmap
Pricing
MSDN forum
Stack Overflow
Videos
Product videos
How to video series
Learn product features and benefits
Migrate your PostgreSQL app to Azure
Build intelligent apps with Cognitive Services
Connect containers using OSBA
Connect your app's data to Power BI
Feedback forum
Region availability
Support options
Customer stories
Partners
Database Migration Guide
What is Azure Database for PostgreSQL?
6/15/2018 • 3 minutes to read • Edit Online

Azure Database for PostgreSQL is a relational database service in the Microsoft cloud built for developers based
on the community version of open-source PostgreSQL database engine. Azure Database for PostgreSQL delivers:
Built-in high availability with no additional cost
Predictable performance, using inclusive pay-as-you-go pricing
Scale as needed within seconds
Secured to protect sensitive data at-rest and in-motion
Automatic backups and point-in-time-restore for up to 35 days
Enterprise-grade security and compliance
All those capabilities require almost no administration, and all are provided at no additional cost. These capabilities
allow you to focus on rapid application development and accelerating your time to market, rather than allocating
precious time and resources to managing virtual machines and infrastructure. In addition, you can continue to
develop your application with the open-source tools and platform of your choice, and deliver with the speed and
efficiency your business demands without having to learn new skills.
This article is an introduction to Azure Database for PostgreSQL core concepts and features related to
performance, scalability, and manageability. See these quickstarts to get you started:
Create an Azure Database for PostgreSQL using Azure portal
Create an Azure Database for PostgreSQL using the Azure CLI
For a set of Azure CLI samples, see:
Azure CLI samples for Azure Database for PostgreSQL

Adjust performance and scale within seconds


Azure Database for PostgreSQL service offers three pricing tiers: Basic, General Purpose, and Memory Optimized.
Each tier offers different resource capabilities to support your database workloads. You can build your first app on
a small database for a few dollars a month, and then adjust the scale to meet the needs of your solution. Dynamic
scalability enables your database to transparently respond to rapidly changing resource requirements. You only
pay for the resources you need, and only when you need them. See Pricing tiers for details.

Monitoring and alerting


How do you decide when to dial up or down? You use the built-in Azure monitoring and alerting features. Using
these tools, you can quickly assess the impact of scaling up or down based on your current or projected
performance or storage needs. See Alerts for details.

Keep your app and business running


Azure's industry leading 99.99% availability service level agreement (SL A), powered by a global network of
Microsoft-managed datacenters, helps keep your app running 24/7. With every Azure Database for PostgreSQL
server, you take advantage of built-in security, fault tolerance, and data protection that you would otherwise have
to buy or design, build, and manage. With Azure Database for PostgreSQL, each pricing tier offers a
comprehensive set of business continuity features and options that you can use to get up and running and stay
that way. You can use point-in-time restore to return a database to an earlier state, as far back as 35 days. In
addition, if the datacenter hosting your databases experiences an outage, you can restore databases from geo-
redundant copies of recent backups.

Secure your data


Azure database services have a tradition of data security that Azure Database for PostgreSQL upholds with
features that limit access, protect data at-rest and in-motion, and help you monitor activity. Visit the Azure Trust
Center for information about Azure's platform security.
The Azure Database for PostgreSQL service uses storage encryption for data at-rest. Data, including backups, is
encrypted on disk (with the exception of temporary files created by the engine while running queries). The service
uses AES 256-bit cipher that is included in Azure storage encryption, and the keys are system managed. Storage
encryption is always on and cannot be disabled.
By default, the Azure Database for PostgreSQL service is configured to require SSL connection security for data
in-motion across the network. Enforcing SSL connections between your database server and your client
applications helps protect against "man in the middle" attacks by encrypting the data stream between the server
and your application. Optionally, you can disable requiring SSL for connecting to your database service if your
client application does not support SSL connectivity.

Contacts
For any questions or suggestions you might have about working with Azure Database for PostgreSQL, send an
email to the Azure Database for PostgreSQL Team (@Ask Azure DB for PostgreSQL ). Note that this is not a
technical support alias.
In addition, consider the following points of contact as appropriate:
To contact Azure Support, file a ticket from the Azure portal.
To fix an issue with your account, file a support request in the Azure portal.
To provide feedback or to request new features, create an entry via UserVoice.

Next steps
See the pricing page for cost comparisons and calculators.
Get started by creating your first Azure Database for PostgreSQL.
Build your first app in Python, PHP, Ruby, C#, Java, Node.js: Connection libraries
Quickstart: Create an Azure Database for
PostgreSQL server in the Azure portal
5/23/2018 • 11 minutes to read • Edit Online

Azure Database for PostgreSQL is a managed service that you use to run, manage, and scale highly available
PostgreSQL databases in the cloud. This Quickstart shows you how to create an Azure Database for PostgreSQL
server in about five minutes using the Azure portal.
If you don't have an Azure subscription, create a free Azure account before you begin.

Sign in to the Azure portal


Open your web browser and go to the portal. Enter your credentials to sign in to the portal. The default view is
your service dashboard.

Create an Azure Database for PostgreSQL server


An Azure Database for PostgreSQL server is created with a configured set of compute and storage resources.
The server is created within an Azure resource group.
To create an Azure Database for PostgreSQL server, take the following steps:
1. Select the Create a resource button (+) in the upper-left corner of the portal.
2. Select Databases > Azure Database for PostgreSQL.

3. Fill out the new server details form with the following information:
SETTING SUGGESTED VALUE DESCRIPTION

Server name mydemoserver A unique name that identifies your


Azure Database for PostgreSQL
server. The domain name
postgres.database.azure.com is
appended to the server name you
provide. The server can contain only
lowercase letters, numbers, and the
hyphen (-) character. It must contain
at least 3 through 63 characters.

Subscription Your subscription name The Azure subscription that you


want to use for your server. If you
have multiple subscriptions, choose
the subscription in which you're
billed for the resource.

Resource group myresourcegroup A new resource group name or an


existing one from your subscription.
SETTING SUGGESTED VALUE DESCRIPTION

Select source Blank Select Blank to create a new server


from scratch. (You would select
Backup if you were creating a server
from a geo-backup of an existing
Azure Database for PostgreSQL
server).

Server admin login myadmin Your own login account to use when
you connect to the server. The
admin login name can't be
azure_superuser,
azure_pg_admin, admin,
administrator, root, guest, or
public. It can't start with pg_.

Password Your password A new password for the server


admin account. It must contain
between 8 and 128 characters. Your
password must contain characters
from three of the following
categories: English uppercase letters,
English lowercase letters, numbers (0
through 9), and non-alphanumeric
characters (!, $, #, %, etc.).

Location The region closest to your users The location that is closest to your
users.

Version The latest version The latest PostgreSQL version,


unless you have specific
requirements otherwise.

Pricing tier General Purpose, Gen 4, 2 vCores, The compute, storage, and backup
5 GB, 7 days, Geographically configurations for your new server.
Redundant Select Pricing tier. Next, select the
General Purpose tab. Gen 4, 2
vCores, 5 GB, and 7 days are the
default values for Compute
Generation, vCore, Storage, and
Backup Retention Period. You can
leave those sliders as is. To enable
your server backups in geo-
redundant storage select
Geographically Redundant from
the Backup Redundancy Options.
To save this pricing tier selection,
select OK. The next screenshot
captures these selections.

IMPORTANT
The server admin login and password that you specify here are required to sign in to the server and its databases
later in this Quickstart. Remember or record this information for later use.
4. Select Create to provision the server. This operation may take a few minutes.
5. On the toolbar, select the Notifications icon (a bell) to monitor the deployment process. Once the
deployment is done, you can select Pin to dashboard, which creates a tile for this server on your Azure
portal dashboard as a shortcut to the server's Overview page. Selecting Go to resource opens the
server's Overview page.

By default, a postgres database is created under your server. The postgres database is a default database
that's meant for use by users, utilities, and third-party applications. (The other default database is
azure_maintenance. Its function is to separate the managed service processes from user actions. You
cannot access this database.)

Configure a server-level firewall rule


Azure Database for PostgreSQL creates a firewall at the server level. It prevents external applications and tools
from connecting to the server and any databases on the server, unless you create a rule to open the firewall for
specific IP addresses.
1. After the deployment finishes, locate your server. If needed, you can search for it. For example, on the
menu on the left, select All resources. Type your server name, such as the example, mydemoserver, to
search for your newly created server. Select your server name from the search result list. The Overview
page for your server opens and provides options for further configuration.
2. On the server page, select Connection security.
3. Under the Firewall rules, in the Rule Name column, select the blank text box to begin creating the
firewall rule.
For this Quickstart, let's allow all IP addresses into the server. Fill in the text box in each column with the
following values:

RULE NAME START IP END IP

AllowAllIps 0.0.0.0 255.255.255.255

4. On the upper toolbar of the Connection security page, select Save. Wait until the notification appears
stating that the connection security update has finished successfully before you continue.
NOTE
Connections to your Azure Database for PostgreSQL server communicate over port 5432. When you try to
connect from within a corporate network, outbound traffic over port 5432 might not be allowed by your network's
firewall. If so, you can't connect to your server unless your IT department opens port 5432.

Get the connection information


When you create your Azure Database for PostgreSQL server, a default database named postgres is created. To
connect to your database server, you need your full server name and admin login credentials. You might have
noted those values earlier in the Quickstart article. If you didn't, you can easily find the server name and login
information on the server Overview page in the portal.
Open your server's Overview page. Make a note of the Server name and the Server admin login name.
Hover your cursor over each field, and the copy symbol appears to the right of the text. Select the copy symbol
as needed to copy the values.

Connect to the PostgreSQL Database by using psql in Cloud Shell


There are a number of applications you can use to connect to your Azure Database for PostgreSQL server. Let's
first use the psql command-line utility to illustrate how to connect to the server. You can use a web browser and
Azure Cloud Shell as described here without the need to install any additional software. If you have the psql
utility installed locally on your own machine, you can connect from there as well.
1. In the top navigation pane, select the terminal symbol to open Cloud Shell.

2. Cloud Shell opens in your browser, where you can type Bash shell commands.

3. At the Cloud Shell prompt, connect to a database in your Azure Database for PostgreSQL server by
typing the psql command line.
To connect to an Azure Database for PostgreSQL server with the psql utility, use the following format:
psql --host=<yourserver> --port=<port> --username=<server admin login> --dbname=<database name>

For example, the following command connects to an example server:

psql --host=mydemoserver.postgres.database.azure.com --port=5432 --username=myadmin@mydemoserver --


dbname=postgres

PSQL PARAMETER VALUE DESCRIPTION

--host Server name The server name value that you


used when you created the Azure
Database for PostgreSQL server
earlier. The example server shown is
mydemoserver.postgres.databas
e.azure.com. Use the fully qualified
domain name
(*.postgres.database.azure.com)
as shown in the example. If you
don't remember your server name,
follow the steps in the previous
section to get the connection
information.

--port 5432 The port to use when you connect


to the Azure Database for
PostgreSQL server.

--username Server admin login name The server admin login username
that you supplied when you created
the Azure Database for PostgreSQL
server earlier. If you don't remember
your username, follow the steps in
the previous section to get the
connection information. The format
is username@servername.

--dbname postgres The default, system-generated


database name that was created for
the first connection. Later, you
create your own database.

After you run the psql command with your own parameter values, you're prompted to enter the server
admin password. This password is the same one that you provided when you created the server.

PSQL PARAMETER SUGGESTED VALUE DESCRIPTION

password Your admin password The typed password characters


aren't shown on the bash prompt.
After you type all the characters, hit
the Enter key to authenticate and
connect.

After you connect, the psql utility displays a postgres prompt where you type sql commands. In the initial
connection output, a warning may appear because the psql in Cloud Shell might be a different version
than the Azure Database for PostgreSQL server version.
Example psql output:
psql (9.5.7, server 9.6.2)
WARNING: psql major version 9.5, server major version 9.6.
Some psql features might not work.
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=>

TIP
If the firewall is not configured to allow the IP address of Cloud Shell, the following error occurs:
"psql: FATAL: no pg_hba.conf entry for host "0.0.0.0", user "myadmin", database "postgres", SSL on FATAL: SSL
connection is required. Specify SSL options and retry.
To resolve the error, make sure the server configuration matches the steps in the "Configure a server-level firewall
rule" section of this article.

4. Create a blank database called "mypgsqldb" at the prompt by typing the following command:

CREATE DATABASE mypgsqldb;

The command might take a few minutes to finish.


5. At the prompt, execute the following command to switch connections to the newly created database
mypgsqldb:

\c mypgsqldb

6. Type \q , and then select the Enter key to quit psql. You can close Cloud Shell after you're finished.

You connected to the Azure Database for PostgreSQL server via psql in Cloud Shell, and you created a blank
user database. Continue to the next section to connect by using another common tool, pgAdmin.

Connect to the PostgreSQL Server using pgAdmin


pgAdmin is an open-source tool used with PostgreSQL. You can install pgAdmin from the pgAdmin website.
The pgAdmin version you're using may be different from what is used in this Quickstart. Read the pgAdmin
documentation if you need additional guidance.
1. Open the pgAdmin application on your client computer.
2. From the toolbar go to Object, hover over Create, and select Server.
3. In the Create - Server dialog box, on the General tab, enter a unique friendly name for the server, such
as mydemoserver.
4. In the Create - Server dialog box, on the Connection tab, fill in the settings table.

PGADMIN PARAMETER VALUE DESCRIPTION

Host name/address Server name The server name value that you
used when you created the Azure
Database for PostgreSQL server
earlier. Our example server is
mydemoserver.postgres.databas
e.azure.com. Use the fully qualified
domain name
(*.postgres.database.azure.com)
as shown in the example. If you
don't remember your server name,
follow the steps in the previous
section to get the connection
information.

Port 5432 The port to use when you connect


to the Azure Database for
PostgreSQL server.

Maintenance database postgres The default system-generated


database name.
PGADMIN PARAMETER VALUE DESCRIPTION

Username Server admin login name The server admin login username
that you supplied when you created
the Azure Database for PostgreSQL
server earlier. If you don't remember
the username, follow the steps in
the previous section to get the
connection information. The format
is username@servername.

Password Your admin password The password you chose when you
created the server earlier in this
Quickstart.

Role Leave blank There's no need to provide a role


name at this point. Leave the field
blank.

SSL mode Require You can set the SSL mode in


pgAdmin's SSL tab. By default, all
Azure Database for PostgreSQL
servers are created with SSL
enforcing turned on. To turn off SSL
enforcing, see SSL Enforcing.

5. Select Save.
6. In the Browser pane on the left, expand the Servers node. Select your server, for example,
mydemoserver. Click to connect to it.
7. Expand the server node, and then expand Databases under it. The list should include your existing
postgres database and any other databases you've created. You can create multiple databases per server
with Azure Database for PostgreSQL.
8. Right-click Databases, choose the Create menu, and then select Database.
9. Type a database name of your choice in the Database field, such as mypgsqldb2.
10. Select the Owner for the database from the list box. Choose your server admin login name, such as the
example, my admin.

11. Select Save to create a new blank database.


12. In the Browser pane, you can see the database that you created in the list of databases under your server
name.

Clean up resources
You can clean up the resources that you created in the Quickstart in one of two ways. You can delete the Azure
resource group, which includes all the resources in the resource group. If you want to keep the other resources
intact, delete only the server resource.

TIP
Other Quickstarts in this collection build on this Quickstart. If you plan to continue working with Quickstarts, don't clean
up the resources that you created in this Quickstart. If you don't plan to continue, follow these steps to delete the
resources that were created by this Quickstart in the portal.

To delete the entire resource group, including the newly created server:
1. Locate your resource group in the portal. On the menu on the left, select Resource groups. Then select
the name of your resource group, such as the example, myresourcegroup.
2. On your resource group page, select Delete. Type the name of your resource group, such as the example,
myresourcegroup, in the text box to confirm deletion. Select Delete.
To delete only the newly created server:
1. Locate your server in the portal, if you don't have it open. On the menu on the left, select All resources.
Then search for the server you created.
2. On the Overview page, select Delete.

3. Confirm the name of the server you want to delete, and view the databases under it that are affected. Type
your server name in the text box, such as the example, mydemoserver. Select Delete.

Next steps
Migrate your database using Export and Import
Quickstart: Create an Azure Database for
PostgreSQL using the Azure CLI
6/27/2018 • 7 minutes to read • Edit Online

Azure Database for PostgreSQL is a managed service that enables you to run, manage, and scale highly available
PostgreSQL databases in the cloud. The Azure CLI is used to create and manage Azure resources from the
command line or in scripts. This quickstart shows you how to create an Azure Database for PostgreSQL server in
an Azure resource group using the Azure CLI.
If you don't have an Azure subscription, create a free account before you begin.

Open Azure Cloud Shell


Azure Cloud Shell is a free, interactive shell that you can use to run the steps in this article. Common Azure tools
are preinstalled and configured in Cloud Shell for you to use with your account. Just select the Copy button to
copy the code, paste it in Cloud Shell, and then press Enter to run it. There are a few ways to open Cloud Shell:

Select Try It in the upper-right corner of a code block.

Open Cloud Shell in your browser.

Select the Cloud Shell button on the menu in the upper-


right corner of the Azure portal.

If you choose to install and use the CLI locally, this article requires that you are running the Azure CLI version 2.0
or later. To see the version installed, run the az --version command. If you need to install or upgrade, see Install
Azure CLI 2.0.
If you are running the CLI locally, you need to log in to your account using the az login command. Note the id
property from the command output for the corresponding subscription name.

az login

If you have multiple subscriptions, choose the appropriate subscription in which the resource should be billed.
Select the specific subscription ID under your account using az account set command. Substitute the id property
from the az login output for your subscription into the subscription id placeholder.

az account set --subscription <subscription id>

Create a resource group


Create an Azure resource group using the az group create command. A resource group is a logical container into
which Azure resources are deployed and managed as a group. You should provide a unique name. The following
example creates a resource group named myresourcegroup in the westus location.
az group create --name myresourcegroup --location westus

Create an Azure Database for PostgreSQL server


Create an Azure Database for PostgreSQL server using the az postgres server create command. A server
contains a group of databases managed as a group.
The following example creates a server in West US named mydemoserver in your resource group
myresourcegroup with server admin login myadmin . This is a Gen 4 General Purpose server with 2 vCores. The
name of a server maps to DNS name and is thus required to be globally unique in Azure. Substitute the
<server_admin_password> with your own value.

az postgres server create --resource-group myresourcegroup --name mydemoserver --location westus --admin-
user myadmin --admin-password <server_admin_password> --sku-name GP_Gen4_2 --version 9.6

The sku-name parameter value follows the convention {pricing tier}_{compute generation}_{vCores} as in the
examples below:
--sku-name B_Gen4_4 maps to Basic, Gen 4, and 4 vCores.
--sku-name GP_Gen5_32 maps to General Purpose, Gen 5, and 32 vCores.
--sku-name MO_Gen5_2 maps to Memory Optimized, Gen 5, and 2 vCores.

Please see the pricing tiers documentation to understand the valid values per region and per tier.

IMPORTANT
The server admin login and password that you specify here are required to log in to the server and its databases later in
this quickstart. Remember or record this information for later use.

By default, postgres database gets created under your server. The postgres database is a default database meant
for use by users, utilities, and third-party applications.

Configure a server-level firewall rule


Create an Azure PostgreSQL server-level firewall rule with the az postgres server firewall-rule create command.
A server-level firewall rule allows an external application, such as psql or PgAdmin to connect to your server
through the Azure PostgreSQL service firewall.
You can set a firewall rule that covers an IP range to be able to connect from your network. The following
example uses az postgres server firewall-rule create to create a firewall rule AllowMyIP for a single IP address.

az postgres server firewall-rule create --resource-group myresourcegroup --server mydemoserver --name


AllowMyIP --start-ip-address 192.168.0.1 --end-ip-address 192.168.0.1

NOTE
Azure PostgreSQL server communicates over port 5432. When connecting from within a corporate network, outbound
traffic over port 5432 may not be allowed by your network's firewall. Have your IT department open port 5432 to connect
to your Azure PostgreSQL server.
Get the connection information
To connect to your server, you need to provide host information and access credentials.

az postgres server show --resource-group myresourcegroup --name mydemoserver

The result is in JSON format. Make a note of the administratorLogin and fullyQualifiedDomainName.

{
"administratorLogin": "myadmin",
"earliestRestoreDate": null,
"fullyQualifiedDomainName": "mydemoserver.postgres.database.azure.com",
"id": "/subscriptions/00000000-0000-0000-0000-
000000000000/resourceGroups/myresourcegroup/providers/Microsoft.DBforPostgreSQL/servers/mydemoserver",
"location": "westus",
"name": "mydemoserver",
"resourceGroup": "myresourcegroup",
"sku": {
"capacity": 2,
"family": "Gen4",
"name": "GP_Gen4_2",
"size": null,
"tier": "GeneralPurpose"
},
"sslEnforcement": "Enabled",
"storageProfile": {
"backupRetentionDays": 7,
"geoRedundantBackup": "Disabled",
"storageMb": 5120
},
"tags": null,
"type": "Microsoft.DBforPostgreSQL/servers",
"userVisibleState": "Ready",
"version": "9.6"
}

Connect to PostgreSQL database using psql


If your client computer has PostgreSQL installed, you can use a local instance of psql to connect to an Azure
PostgreSQL server. Let's now use the psql command-line utility to connect to the Azure PostgreSQL server.
1. Run the following psql command to connect to an Azure Database for PostgreSQL server

psql --host=<servername> --port=<port> --username=<user@servername> --dbname=<dbname>

For example, the following command connects to the default database called postgres on your
PostgreSQL server mydemoserver.postgres.database.azure.com using access credentials. Enter the
<server_admin_password> you chose when prompted for password.

psql --host=mydemoserver.postgres.database.azure.com --port=5432 --username=myadmin@mydemoserver --


dbname=postgres

2. Once you are connected to the server, create a blank database at the prompt.

CREATE DATABASE mypgsqldb;

3. At the prompt, execute the following command to switch connection to the newly created database
mypgsqldb:

\c mypgsqldb

Connect to the PostgreSQL Server using pgAdmin


pgAdmin is an open-source tool used with PostgreSQL. You can install pgAdmin from the pgAdmin website. The
pgAdmin version you're using may be different from what is used in this Quickstart. Read the pgAdmin
documentation if you need additional guidance.
1. Open the pgAdmin application on your client computer.
2. From the toolbar go to Object, hover over Create, and select Server.
3. In the Create - Server dialog box, on the General tab, enter a unique friendly name for the server, such as
mydemoserver.

4. In the Create - Server dialog box, on the Connection tab, fill in the settings table.

PGADMIN PARAMETER VALUE DESCRIPTION


PGADMIN PARAMETER VALUE DESCRIPTION

Host name/address Server name The server name value that you
used when you created the Azure
Database for PostgreSQL server
earlier. Our example server is
mydemoserver.postgres.databas
e.azure.com. Use the fully qualified
domain name
(*.postgres.database.azure.com)
as shown in the example. If you
don't remember your server name,
follow the steps in the previous
section to get the connection
information.

Port 5432 The port to use when you connect


to the Azure Database for
PostgreSQL server.

Maintenance database postgres The default system-generated


database name.

Username Server admin login name The server admin login username
that you supplied when you created
the Azure Database for PostgreSQL
server earlier. If you don't remember
the username, follow the steps in the
previous section to get the
connection information. The format
is username@servername.

Password Your admin password The password you chose when you
created the server earlier in this
Quickstart.

Role Leave blank There's no need to provide a role


name at this point. Leave the field
blank.

SSL mode Require You can set the SSL mode in


pgAdmin's SSL tab. By default, all
Azure Database for PostgreSQL
servers are created with SSL
enforcing turned on. To turn off SSL
enforcing, see SSL Enforcing.

5. Select Save.
6. In the Browser pane on the left, expand the Servers node. Select your server, for example,
mydemoserver. Click to connect to it.
7. Expand the server node, and then expand Databases under it. The list should include your existing
postgres database and any other databases you've created. You can create multiple databases per server
with Azure Database for PostgreSQL.
8. Right-click Databases, choose the Create menu, and then select Database.
9. Type a database name of your choice in the Database field, such as mypgsqldb2.
10. Select the Owner for the database from the list box. Choose your server admin login name, such as the
example, my admin.

11. Select Save to create a new blank database.


12. In the Browser pane, you can see the database that you created in the list of databases under your server
name.

Clean up resources
Clean up all resources you created in the quickstart by deleting the Azure resource group.

TIP
Other quickstarts in this collection build upon this quickstart. If you plan to continue to work with subsequent quickstarts,
do not clean up the resources created in this quickstart. If you do not plan to continue, use the following steps to delete all
resources created by this quickstart in the Azure CLI.

az group delete --name myresourcegroup

If you would just like to delete the one newly created server, you can run az postgres server delete command.

az postgres server delete --resource-group myresourcegroup --name mydemoserver

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Python to
connect and query data
2/27/2018 • 5 minutes to read • Edit Online

This quickstart demonstrates how to use Python to connect to an Azure Database for PostgreSQL. It also
demonstrates how to use SQL statements to query, insert, update, and delete data in the database from macOS,
Ubuntu Linux, and Windows platforms. The steps in this article assume that you are familiar with developing using
Python and are new to working with Azure Database for PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - CLI
You also need:
python installed
pip package installed (pip is already installed if you're working with Python 2 >=2.7.9 or Python 3 >=3.4
binaries downloaded from python.org.

Install the Python connection libraries for PostgreSQL


Install the psycopg2 package, which enables you to connect and query the database. psycopg2 is available on PyPI
in the form of wheel packages for the most common platforms (Linux, OSX, Windows). Use pip install to get the
binary version of the module including all the dependencies.
1. On your own computer, launch a command-line interface:
On Linux, launch the Bash shell.
On macOS, launch the Terminal.
On Windows, launch the Command Prompt from the Start Menu.
2. Ensure that you are using the most current version of pip by running a command such as:

pip install -U pip

3. Run the following command to install the psycopg2 package:

pip install psycopg2

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created
(such as mydemoserver).
3. Click the server name.
4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you
forget your password, you can also reset the password from this panel.

How to run Python code


This article contains a total of four code samples, each of which performs a specific function. The following
instructions indicate how to create a text file, insert a code block, and then save the file so that you can run it later.
Be sure to create four separate files, one for each code block.
Using your favorite text editor, create a new file.
Copy and paste one of the code samples in the following sections into the text file. Replace the host, dbname,
user, and password parameters with the values that you specified when you created the server and database.
Save the file with the .py extension (for example postgres.py) into your project folder. If you are running on
Windows, be sure to select UTF -8 encoding when saving the file.
Launch the Command Prompt, Terminal, or Bash shell and then change the directory to your project folder, for
example cd postgres .
To run the code, type the Python command followed by the file name, for example Python postgres.py .

NOTE
Starting in Python version 3, you may see the error SyntaxError: Missing parentheses in call to 'print' when
running the following code blocks: If that happens, replace each call to the command print "string" with a function call
using parenthesis, such as print("string") .

Connect, create table, and insert data


Use the following code to connect and load the data using psycopg2.connect function with INSERT SQL
statement. The cursor.execute function is used to execute the SQL query against PostgreSQL database. Replace the
host, dbname, user, and password parameters with the values that you specified when you created the server and
database.
import psycopg2

# Update connection string information obtained from the portal


host = "mydemoserver.postgres.database.azure.com"
user = "mylogin@mydemoserver"
dbname = "mypgsqldb"
password = "<server_admin_password>"
sslmode = "require"

# Construct connection string


conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password,
sslmode)
conn = psycopg2.connect(conn_string)
print "Connection established"

cursor = conn.cursor()

# Drop previous table of same name if one exists


cursor.execute("DROP TABLE IF EXISTS inventory;")
print "Finished dropping table (if existed)"

# Create table
cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
print "Finished creating table"

# Insert some data into table


cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
print "Inserted 3 rows of data"

# Cleanup
conn.commit()
cursor.close()
conn.close()

After the code runs successfully, the output appears as follows:

Read data
Use the following code to read the data inserted using cursor.execute function with SELECT SQL statement. This
function accepts a query and returns a result set that can be iterated over with the use of cursor.fetchall(). Replace
the host, dbname, user, and password parameters with the values that you specified when you created the server
and database.
import psycopg2

# Update connection string information obtained from the portal


host = "mydemoserver.postgres.database.azure.com"
user = "mylogin@mydemoserver"
dbname = "mypgsqldb"
password = "<server_admin_password>"
sslmode = "require"

# Construct connection string


conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password,
sslmode)
conn = psycopg2.connect(conn_string)
print "Connection established"

cursor = conn.cursor()

# Fetch all rows from table


cursor.execute("SELECT * FROM inventory;")
rows = cursor.fetchall()

# Print all rows


for row in rows:
print "Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2]))

# Cleanup
conn.commit()
cursor.close()
conn.close()

Update data
Use the following code to update the inventory row that you previously inserted using cursor.execute function with
UPDATE SQL statement. Replace the host, dbname, user, and password parameters with the values that you
specified when you created the server and database.

import psycopg2

# Update connection string information obtained from the portal


host = "mydemoserver.postgres.database.azure.com"
user = "mylogin@mydemoserver"
dbname = "mypgsqldb"
password = "<server_admin_password>"
sslmode = "require"

# Construct connection string


conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password,
sslmode)
conn = psycopg2.connect(conn_string)
print "Connection established"

cursor = conn.cursor()

# Update a data row in the table


cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (200, "banana"))
print "Updated 1 row of data"

# Cleanup
conn.commit()
cursor.close()
conn.close()
Delete data
Use the following code to delete an inventory item that you previously inserted using cursor.execute function with
DELETE SQL statement. Replace the host, dbname, user, and password parameters with the values that you
specified when you created the server and database.

import psycopg2

# Update connection string information obtained from the portal


host = "mydemoserver.postgres.database.azure.com"
user = "mylogin@mydemoserver"
dbname = "mypgsqldb"
password = "<server_admin_password>"
sslmode = "require"

# Construct connection string


conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password,
sslmode)
conn = psycopg2.connect(conn_string)
print "Connection established"

cursor = conn.cursor()

# Delete data row from table


cursor.execute("DELETE FROM inventory WHERE name = %s;", ("orange",))
print "Deleted 1 row of data"

# Cleanup
conn.commit()
cursor.close()
conn.close()

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Node.js to
connect and query data
2/27/2018 • 4 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a Node.js application. It
shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article
assume that you are familiar with developing using Node.js, and are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - CLI
You also need to:
Install Node.js

Install pg client
Install pg, which is a PostgreSQL client for Node.js.
To do so, run the node package manager (npm) for JavaScript from your command line to install the pg client.

npm install pg

Verify the installation by listing the packages installed.

npm list

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created
(such as mydemoserver).
3. Click the server name.
4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you
forget your password, you can also reset the password from this panel.
Running the JavaScript code in Node.js
You may launch Node.js from the Bash shell, Terminal, or Windows Command Prompt by typing node , then run
the example JavaScript code interactively by copy and pasting it onto the prompt. Alternatively, you may save the
JavaScript code into a text file and launch node filename.js with the file name as a parameter to run it.

Connect, create table, and insert data


Use the following code to connect and load the data using CREATE TABLE and INSERT INTO SQL statements.
The pg.Client object is used to interface with the PostgreSQL server. The pg.Client.connect() function is used to
establish the connection to the server. The pg.Client.query() function is used to execute the SQL query against
PostgreSQL database.
Replace the host, dbname, user, and password parameters with the values that you specified when you created the
server and database.
const pg = require('pg');

const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
if (err) throw err;
else {
queryDatabase();
}
});

function queryDatabase() {
const query = `
DROP TABLE IF EXISTS inventory;
CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);
INSERT INTO inventory (name, quantity) VALUES ('banana', 150);
INSERT INTO inventory (name, quantity) VALUES ('orange', 154);
INSERT INTO inventory (name, quantity) VALUES ('apple', 100);
`;

client
.query(query)
.then(() => {
console.log('Table created successfully!');
client.end(console.log('Closed client connection'));
})
.catch(err => console.log(err))
.then(() => {
console.log('Finished execution, exiting now');
process.exit();
});
}

Read data
Use the following code to connect and read the data using a SELECT SQL statement. The pg.Client object is used
to interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the
server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.
Replace the host, dbname, user, and password parameters with the values that you specified when you created the
server and database.
const pg = require('pg');

const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
if (err) throw err;
else { queryDatabase(); }
});

function queryDatabase() {

console.log(`Running query to PostgreSQL server: ${config.host}`);

const query = 'SELECT * FROM inventory;';

client.query(query)
.then(res => {
const rows = res.rows;

rows.map(row => {
console.log(`Read: ${JSON.stringify(row)}`);
});

process.exit();
})
.catch(err => {
console.log(err);
});
}

Update data
Use the following code to connect and read the data using a UPDATE SQL statement. The pg.Client object is used
to interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the
server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.
Replace the host, dbname, user, and password parameters with the values that you specified when you created the
server and database.
const pg = require('pg');

const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
if (err) throw err;
else {
queryDatabase();
}
});

function queryDatabase() {
const query = `
UPDATE inventory
SET quantity= 1000 WHERE name='banana';
`;

client
.query(query)
.then(result => {
console.log('Update completed');
console.log(`Rows affected: ${result.rowCount}`);
})
.catch(err => {
console.log(err);
throw err;
});
}

Delete data
Use the following code to connect and read the data using a DELETE SQL statement. The pg.Client object is used
to interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the
server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.
Replace the host, dbname, user, and password parameters with the values that you specified when you created the
server and database.
const pg = require('pg');

const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
if (err) {
throw err;
} else {
queryDatabase();
}
});

function queryDatabase() {
const query = `
DELETE FROM inventory
WHERE name = 'apple';
`;

client
.query(query)
.then(result => {
console.log('Delete completed');
console.log(`Rows affected: ${result.rowCount}`);
})
.catch(err => {
console.log(err);
throw err;
});
}

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Java to connect
and query data
2/27/2018 • 7 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a Java application. It
shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article
assume that you are familiar with developing using Java, and are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - Azure CLI
You also need to:
Download the PostgreSQL JDBC Driver matching your version of Java and the Java Development Kit.
Include the PostgreSQL JDBC jar file (for example postgresql-42.1.1.jar) in your application classpath. For more
information, see classpath details.

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created
(such as mydemoserver).
3. Click the server name.
4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you
forget your password, you can also reset the password from this panel.

Connect, create table, and insert data


Use the following code to connect and load the data into the database using the function with an INSERT SQL
statement. The methods getConnection(), createStatement(), and executeQuery() are used to connect to the
database, drop, and create the table. The prepareStatement object is used to build the insert commands, with
setString() and setInt() to bind the parameter values. Method executeUpdate() runs the command for each set of
parameters.
Replace the host, database, user, and password parameters with the values that you specified when you created
your own server and database.

import java.sql.*;
import java.util.Properties;

public class CreateTableInsertRows {

public static void main (String[] args) throws Exception


{

// Initialize connection variables.


String host = "mydemoserver.postgres.database.azure.com";
String database = "mypgsqldb";
String user = "mylogin@mydemoserver";
String password = "<server_admin_password>";

// check that the driver is installed


try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);
}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object


try
{
String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties


Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("ssl", "true");

// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection.


try
{
// Drop previous table of same name if one exists.
Statement statement = connection.createStatement();
statement.execute("DROP TABLE IF EXISTS inventory;");
System.out.println("Finished dropping table (if existed).");

// Create table.
statement.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity
INTEGER);");
System.out.println("Created table.");

// Insert some data into table.


int nRowsInserted = 0;
int nRowsInserted = 0;
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO inventory (name,
quantity) VALUES (?, ?);");
preparedStatement.setString(1, "banana");
preparedStatement.setInt(2, 150);
nRowsInserted += preparedStatement.executeUpdate();

preparedStatement.setString(1, "orange");
preparedStatement.setInt(2, 154);
nRowsInserted += preparedStatement.executeUpdate();

preparedStatement.setString(1, "apple");
preparedStatement.setInt(2, 100);
nRowsInserted += preparedStatement.executeUpdate();
System.out.println(String.format("Inserted %d row(s) of data.", nRowsInserted));

// NOTE No need to commit all changes to database, as auto-commit is enabled by default.

}
catch (SQLException e)
{
throw new SQLException("Encountered an error when executing given sql statement.", e);
}
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
}

Read data
Use the following code to read the data with a SELECT SQL statement. The methods getConnection(),
createStatement(), and executeQuery() are used to connect to the database, create, and run the select statement.
The results are processed using a ResultSet object.
Replace the host, database, user, and password parameters with the values that you specified when you created
your own server and database.

import java.sql.*;
import java.util.Properties;

public class ReadTable {

public static void main (String[] args) throws Exception


{

// Initialize connection variables.


String host = "mydemoserver.postgres.database.azure.com";
String database = "mypgsqldb";
String user = "mylogin@mydemoserver";
String password = "<server_admin_password>";

// check that the driver is installed


try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);
}

System.out.println("PostgreSQL JDBC driver detected in library path.");


Connection connection = null;

// Initialize connection object


try
{
String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties


Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("ssl", "true");

// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection.


try
{

Statement statement = connection.createStatement();


ResultSet results = statement.executeQuery("SELECT * from inventory;");
while (results.next())
{
String outputString =
String.format(
"Data row = (%s, %s, %s)",
results.getString(1),
results.getString(2),
results.getString(3));
System.out.println(outputString);
}
}
catch (SQLException e)
{
throw new SQLException("Encountered an error when executing given sql statement.", e);
}
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
}

Update data
Use the following code to change the data with an UPDATE SQL statement. The methods getConnection(),
prepareStatement(), and executeUpdate() are used to connect to the database, prepare, and run the update
statement.
Replace the host, database, user, and password parameters with the values that you specified when you created
your own server and database.

import java.sql.*;
import java.util.Properties;
public class UpdateTable {
public static void main (String[] args) throws Exception
{

// Initialize connection variables.


String host = "mydemoserver.postgres.database.azure.com";
String database = "mypgsqldb";
String user = "mylogin@mydemoserver";
String password = "<server_admin_password>";

// check that the driver is installed


try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);
}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object


try
{
String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties


Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("ssl", "true");

// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection.


try
{
// Modify some data in table.
int nRowsUpdated = 0;
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE inventory SET
quantity = ? WHERE name = ?;");
preparedStatement.setInt(1, 200);
preparedStatement.setString(2, "banana");
nRowsUpdated += preparedStatement.executeUpdate();
System.out.println(String.format("Updated %d row(s) of data.", nRowsUpdated));

// NOTE No need to commit all changes to database, as auto-commit is enabled by default.


}
catch (SQLException e)
{
throw new SQLException("Encountered an error when executing given sql statement.", e);
}
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
System.out.println("Execution finished.");
}
}

Delete data
Use the following code to remove data with a DELETE SQL statement. The methods getConnection(),
prepareStatement(), and executeUpdate() are used to connect to the database, prepare, and run the delete
statement.
Replace the host, database, user, and password parameters with the values that you specified when you created
your own server and database.

import java.sql.*;
import java.util.Properties;

public class DeleteTable {


public static void main (String[] args) throws Exception
{

// Initialize connection variables.


String host = "mydemoserver.postgres.database.azure.com";
String database = "mypgsqldb";
String user = "mylogin@mydemoserver";
String password = "<server_admin_password>";

// check that the driver is installed


try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);
}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object


try
{
String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties


Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("ssl", "true");

// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection.


try
{
// Delete some data from table.
// Delete some data from table.
int nRowsDeleted = 0;
PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM inventory WHERE
name = ?;");
preparedStatement.setString(1, "orange");
nRowsDeleted += preparedStatement.executeUpdate();
System.out.println(String.format("Deleted %d row(s) of data.", nRowsDeleted));

// NOTE No need to commit all changes to database, as auto-commit is enabled by default.


}
catch (SQLException e)
{
throw new SQLException("Encountered an error when executing given sql statement.", e);
}
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
}

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Ruby to connect
and query data
2/27/2018 • 6 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a Ruby application. It
shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article
assume that you are familiar with developing using Ruby, and are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - Azure CLI

Install Ruby
Install Ruby on your own machine.
Windows
Download and Install the latest version of Ruby.
On the finish screen of the MSI installer, check the box that says "Run 'ridk install' to install MSYS2 and
development toolchain." Then click Finish to launch the next installer.
The RubyInstaller2 for Windows installer launches. Type 2 to install the MSYS2 repository update. After it
finishes and returns to the installation prompt, close the command window.
Launch a new command prompt (cmd) from the Start menu.
Test the Ruby installation ruby -v to see the version installed.
Test the Gem installation gem -v to see the version installed.
Build the PostgreSQL module for Ruby using Gem by running the command gem install pg .
MacOS
Install Ruby using Homebrew by running the command brew install ruby . For more installation options, see
the Ruby installation documentation
Test the Ruby installation ruby -v to see the version installed.
Test the Gem installation gem -v to see the version installed.
Build the PostgreSQL module for Ruby using Gem by running the command gem install pg .
Linux (Ubuntu)
Install Ruby by running the command sudo apt-get install ruby-full . For more installation options, see the
Ruby installation documentation.
Test the Ruby installation ruby -v to see the version installed.
Install the latest updates for Gem by running the command sudo gem update --system .
Test the Gem installation gem -v to see the version installed.
Install the gcc, make, and other build tools by running the command sudo apt-get install build-essential .
Install the PostgreSQL libraries by running the command sudo apt-get install libpq-dev .
Build the Ruby pg module using Gem by running the command sudo gem install pg .
Run Ruby code
Save the code into a text file with file extension .rb, and save the file into a project folder, such as
C:\rubypostgres\read.rb or /home/username/rubypostgres/read.rb
To run the code, launch the command prompt or bash shell. Change directory into your project folder
cd rubypostgres , then type the command ruby read.rb to run the application.

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created
(such as mydemoserver).
3. Click the server name.
4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you
forget your password, you can also reset the password from this panel.

Connect and create a table


Use the following code to connect and create a table using CREATE TABLE SQL statement, followed by INSERT
INTO SQL statements to add rows into the table.
The code uses a PG::Connection object with constructor new () to connect to Azure Database for PostgreSQL. Then
it calls method exec() to run the DROP, CREATE TABLE, and INSERT INTO commands. The code checks for errors
using the PG::Error class. Then it calls method close() to close the connection before terminating.
Replace the host , database , user , and password strings with your own values.
require 'pg'

begin
# Initialize connection variables.
host = String('mydemoserver.postgres.database.azure.com')
database = String('postgres')
user = String('mylogin@mydemoserver')
password = String('<server_admin_password>')

# Initialize connection object.


connection = PG::Connection.new(:host => host, :user => user, :dbname => database, :port => '5432',
:password => password)
puts 'Successfully created connection to database'

# Drop previous table of same name if one exists


connection.exec('DROP TABLE IF EXISTS inventory;')
puts 'Finished dropping table (if existed).'

# Drop previous table of same name if one exists.


connection.exec('CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);')
puts 'Finished creating table.'

# Insert some data into table.


connection.exec("INSERT INTO inventory VALUES(1, 'banana', 150)")
connection.exec("INSERT INTO inventory VALUES(2, 'orange', 154)")
connection.exec("INSERT INTO inventory VALUES(3, 'apple', 100)")
puts 'Inserted 3 rows of data.'

rescue PG::Error => e


puts e.message

ensure
connection.close if connection
end

Read data
Use the following code to connect and read the data using a SELECT SQL statement.
The code uses a PG::Connection object with constructor new () to connect to Azure Database for PostgreSQL. Then
it calls method exec() to run the SELECT command, keeping the results in a result set. The result set collection is
iterated over using the resultSet.each do loop, keeping the current row values in the row variable. The code
checks for errors using the PG::Error class. Then it calls method close() to close the connection before terminating.
Replace the host , database , user , and password strings with your own values.
require 'pg'

begin
# Initialize connection variables.
host = String('mydemoserver.postgres.database.azure.com')
database = String('postgres')
user = String('mylogin@mydemoserver')
password = String('<server_admin_password>')

# Initialize connection object.


connection = PG::Connection.new(:host => host, :user => user, :database => dbname, :port => '5432',
:password => password)
puts 'Successfully created connection to database.'

resultSet = connection.exec('SELECT * from inventory;')


resultSet.each do |row|
puts 'Data row = (%s, %s, %s)' % [row['id'], row['name'], row['quantity']]
end

rescue PG::Error => e


puts e.message

ensure
connection.close if connection
end

Update data
Use the following code to connect and update the data using a UPDATE SQL statement.
The code uses a PG::Connection object with constructor new () to connect to Azure Database for PostgreSQL. Then
it calls method exec() to run the UPDATE command. The code checks for errors using the PG::Error class. Then it
calls method close() to close the connection before terminating.
Replace the host , database , user , and password strings with your own values.

require 'pg'

begin
# Initialize connection variables.
host = String('mydemoserver.postgres.database.azure.com')
database = String('postgres')
user = String('mylogin@mydemoserver')
password = String('<server_admin_password>')

# Initialize connection object.


connection = PG::Connection.new(:host => host, :user => user, :dbname => database, :port => '5432',
:password => password)
puts 'Successfully created connection to database.'

# Modify some data in table.


connection.exec('UPDATE inventory SET quantity = %d WHERE name = %s;' % [200, '\'banana\''])
puts 'Updated 1 row of data.'

rescue PG::Error => e


puts e.message

ensure
connection.close if connection
end
Delete data
Use the following code to connect and read the data using a DELETE SQL statement.
The code uses a PG::Connection object with constructor new () to connect to Azure Database for PostgreSQL. Then
it calls method exec() to run the UPDATE command. The code checks for errors using the PG::Error class. Then it
calls method close() to close the connection before terminating.
Replace the host , database , user , and password strings with your own values.

require 'pg'

begin
# Initialize connection variables.
host = String('mydemoserver.postgres.database.azure.com')
database = String('postgres')
user = String('mylogin@mydemoserver')
password = String('<server_admin_password>')

# Initialize connection object.


connection = PG::Connection.new(:host => host, :user => user, :dbname => database, :port => '5432',
:password => password)
puts 'Successfully created connection to database.'

# Modify some data in table.


connection.exec('DELETE FROM inventory WHERE name = %s;' % ['\'orange\''])
puts 'Deleted 1 row of data.'

rescue PG::Error => e


puts e.message

ensure
connection.close if connection
end

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use PHP to connect
and query data
2/27/2018 • 6 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a PHP application. It
shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article
assume that you are familiar with developing using PHP, and are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - Azure CLI

Install PHP
Install PHP on your own server, or create an Azure web app that includes PHP.
Windows
Download PHP 7.1.4 non-thread safe (x64) version
Install PHP and refer to the PHP manual for further configuration
The code uses the pgsql class (ext/php_pgsql.dll) that is included in the PHP installation.
Enabled the pgsql extension by editing the php.ini configuration file, typically located at
C:\Program Files\PHP\v7.1\php.ini . The configuration file should contain a line with the text
extension=php_pgsql.so . If it is not shown, add the text and save the file. If the text is present, but commented
with a semicolon prefix, uncomment the text by removing the semicolon.
Linux (Ubuntu)
Download PHP 7.1.4 non-thread safe (x64) version
Install PHP and refer to the PHP manual for further configuration
The code uses the pgsql class (php_pgsql.so). Install it by running sudo apt-get install php-pgsql .
Enabled the pgsql extension by editing the /etc/php/7.0/mods-available/pgsql.ini configuration file. The
configuration file should contain a line with the text extension=php_pgsql.so . If it is not shown, add the text and
save the file. If the text is present, but commented with a semicolon prefix, uncomment the text by removing the
semicolon.
MacOS
Download PHP 7.1.4 version
Install PHP and refer to the PHP manual for further configuration

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created
(such as mydemoserver).
3. Click the server name.
4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you
forget your password, you can also reset the password from this panel.

Connect and create a table


Use the following code to connect and create a table using CREATE TABLE SQL statement, followed by INSERT
INTO SQL statements to add rows into the table.
The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query()
several times to run several commands, and pg_last_error() to check the details if an error occurred each time. Then
it calls method pg_close() to close the connection.
Replace the $host , $database , $user , and $password parameters with your own values.
<?php
// Initialize connection variables.
$host = "mydemoserver.postgres.database.azure.com";
$database = "mypgsqldb";
$user = "mylogin@mydemoserver";
$password = "<server_admin_password>";

// Initialize connection object.


$connection = pg_connect("host=$host dbname=$database user=$user password=$password")
or die("Failed to create connection to database: ". pg_last_error(). "<br/>");
print "Successfully created connection to database.<br/>";

// Drop previous table of same name if one exists.


$query = "DROP TABLE IF EXISTS inventory;";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");
print "Finished dropping table (if existed).<br/>";

// Create table.
$query = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");
print "Finished creating table.<br/>";

// Insert some data into table.


$name = '\'banana\'';
$quantity = 150;
$query = "INSERT INTO inventory (name, quantity) VALUES ($1, $2);";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");

$name = '\'orange\'';
$quantity = 154;
$query = "INSERT INTO inventory (name, quantity) VALUES ($name, $quantity);";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");

$name = '\'apple\'';
$quantity = 100;
$query = "INSERT INTO inventory (name, quantity) VALUES ($name, $quantity);";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error()). "<br/>";

print "Inserted 3 rows of data.<br/>";

// Closing connection
pg_close($connection);
?>

Read data
Use the following code to connect and read the data using a SELECT SQL statement.
The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query()
to run the SELECT command, keeping the results in a result set, and pg_last_error() to check the details if an error
occurred. To read the result set, method pg_fetch_row () is called in a loop, once per row, and the row data is
retrieved in an array $row , with one data value per column in each array position. To free the result set, method
pg_free_result() is called. Then it calls method pg_close() to close the connection.
Replace the $host , $database , $user , and $password parameters with your own values.
<?php
// Initialize connection variables.
$host = "mydemoserver.postgres.database.azure.com";
$database = "mypgsqldb";
$user = "mylogin@mydemoserver";
$password = "<server_admin_password>";

// Initialize connection object.


$connection = pg_connect("host=$host dbname=$database user=$user password=$password")
or die("Failed to create connection to database: ". pg_last_error(). "<br/>");

print "Successfully created connection to database. <br/>";

// Perform some SQL queries over the connection.


$query = "SELECT * from inventory";
$result_set = pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");
while ($row = pg_fetch_row($result_set))
{
print "Data row = ($row[0], $row[1], $row[2]). <br/>";
}

// Free result_set
pg_free_result($result_set);

// Closing connection
pg_close($connection);
?>

Update data
Use the following code to connect and update the data using a UPDATE SQL statement.
The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query()
to run a command, and pg_last_error() to check the details if an error occurred. Then it calls method pg_close() to
close the connection.
Replace the $host , $database , $user , and $password parameters with your own values.

<?php
// Initialize connection variables.
$host = "mydemoserver.postgres.database.azure.com";
$database = "mypgsqldb";
$user = "mylogin@mydemoserver";
$password = "<server_admin_password>";

// Initialize connection object.


$connection = pg_connect("host=$host dbname=$database user=$user password=$password")
or die("Failed to create connection to database: ". pg_last_error(). ".<br/>");

print "Successfully created connection to database. <br/>";

// Modify some data in table.


$new_quantity = 200;
$name = '\'banana\'';
$query = "UPDATE inventory SET quantity = $new_quantity WHERE name = $name;";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). ".<br/>");
print "Updated 1 row of data. </br>";

// Closing connection
pg_close($connection);
?>
Delete data
Use the following code to connect and read the data using a DELETE SQL statement.
The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query()
to run a command, and pg_last_error() to check the details if an error occurred. Then it calls method pg_close() to
close the connection.
Replace the $host , $database , $user , and $password parameters with your own values.

<?php
// Initialize connection variables.
$host = "mydemoserver.postgres.database.azure.com";
$database = "mypgsqldb";
$user = "mylogin@mydemoserver";
$password = "<server_admin_password>";

// Initialize connection object.


$connection = pg_connect("host=$host dbname=$database user=$user password=$password")
or die("Failed to create connection to database: ". pg_last_error(). ". </br>");

print "Successfully created connection to database. <br/>";

// Delete some data from table.


$name = '\'orange\'';
$query = "DELETE FROM inventory WHERE name = $name;";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). ". <br/>");
print "Deleted 1 row of data. <br/>";

// Closing connection
pg_close($connection);
?>

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use .NET (C#) to
connect and query data
2/27/2018 • 5 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a C# application. It
shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article
assume that you are familiar with developing using C#, and that you are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - CLI
You also need to:
Install the .NET Framework. Follow the steps in the linked article to install .NET specifically for your platform
(Windows, Ubuntu Linux, or macOS ).
Install Visual Studio or Visual Studio Code to type and edit code.
Add a reference to the Npgsql Nuget package.

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created
(such as mydemoserver).
3. Click the server name.
4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you
forget your password, you can also reset the password from this panel.

Connect, create table, and insert data


Use the following code to connect and load the data using CREATE TABLE and INSERT INTO SQL statements.
The code uses NpgsqlCommand class with method Open() to establish a connection to the PostgreSQL database.
Then the code uses method CreateCommand(), sets the CommandText property, and calls the ExecuteNonQuery()
method to run the database commands.
Replace the Host, DBName, User, and Password parameters with the values that you specified when you created
the server and database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;

namespace Driver
{
public class AzurePostgresCreate
{
// Obtain connection string information from the portal
//
private static string Host = "mydemoserver.postgres.database.azure.com";
private static string User = "mylogin@mydemoserver";
private static string DBname = "mypgsqldb";
private static string Password = "<server_admin_password>";
private static string Port = "5432";

static void Main(string[] args)


{
// Build connection string using parameters from portal
//
string connString =
String.Format(
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4}; SSL Mode=Prefer; Trust
Server Certificate=true",
Host,
User,
DBname,
Port,
Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection");
conn.Open();

var command = conn.CreateCommand();


command.CommandText = "DROP TABLE IF EXISTS inventory;";
command.ExecuteNonQuery();
Console.Out.WriteLine("Finished dropping table (if existed)");

command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity
INTEGER);";
command.ExecuteNonQuery();
Console.Out.WriteLine("Finished creating table");

command.CommandText =
String.Format(
@"
INSERT INTO inventory (name, quantity) VALUES ({0}, {1});
INSERT INTO inventory (name, quantity) VALUES ({2}, {3});
INSERT INTO inventory (name, quantity) VALUES ({4}, {5});
",
"\'banana\'", 150,
"\'orange\'", 154,
"\'apple\'", 100
);

int nRows = command.ExecuteNonQuery();


Console.Out.WriteLine(String.Format("Number of rows inserted={0}", nRows));

Console.Out.WriteLine("Closing connection");
conn.Close();
conn.Close();

Console.WriteLine("Press RETURN to exit");


Console.ReadLine();
}
}
}

Read data
Use the following code to connect and read the data using a SELECT SQL statement. The code uses
NpgsqlCommand class with method Open() to establish a connection to PostgreSQL. Then the code uses the
methods CreateCommand() and ExecuteReader() to run the database commands. Next, the code uses Read() to
advance to the record in the results. Finally, the code uses GetInt32() and GetString() to parse the values in the
record.
Replace the Host, DBName, User, and Password parameters with the values that you specified when you created
the server and database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;

namespace Driver
{
public class AzurePostgresRead
{
// Obtain connection string information from the portal
//
private static string Host = "mydemoserver.postgres.database.azure.com";
private static string User = "mylogin@mydemoserver";
private static string DBname = "mypgsqldb";
private static string Password = "<server_admin_password>";
private static string Port = "5432";

static void Main(string[] args)


{
// Build connection string using parameters from portal
//
string connString =
String.Format(
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};",
Host,
User,
DBname,
Port,
Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection");
conn.Open();

var command = conn.CreateCommand();


command.CommandText = "SELECT * FROM inventory;";

var reader = command.ExecuteReader();


while (reader.Read())
{
Console.WriteLine(
string.Format(
"Reading from table=({0}, {1}, {2})",
reader.GetInt32(0).ToString(),
reader.GetString(1),
reader.GetInt32(2).ToString()
)
);
}

Console.Out.WriteLine("Closing connection");
conn.Close();

Console.WriteLine("Press RETURN to exit");


Console.ReadLine();
}
}
}

Update data
Use the following code to connect and update the data using an UPDATE SQL statement. The code uses
NpgsqlCommand class with method Open() to establish a connection to PostgreSQL. Then, the code uses method
CreateCommand(), sets the CommandText property, and calls the ExecuteNonQuery() method to run the database
commands.
Replace the Host, DBName, User, and Password parameters with the values that you specified when you created
the server and database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;

namespace Driver
{
public class AzurePostgresUpdate
{
// Obtain connection string information from the portal
//
private static string Host = "mydemoserver.postgres.database.azure.com";
private static string User = "mylogin@mydemoserver";
private static string DBname = "mypgsqldb";
private static string Password = "<server_admin_password>";
private static string Port = "5432";

static void Main(string[] args)


{
// Build connection string using parameters from portal
//
string connString =
String.Format(
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};",
Host,
User,
DBname,
Port,
Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection");
conn.Open();

var command = conn.CreateCommand();


command.CommandText =
String.Format("UPDATE inventory SET quantity = {0} WHERE name = {1};",
200,
"\'banana\'"
);

int nRows = command.ExecuteNonQuery();


Console.Out.WriteLine(String.Format("Number of rows updated={0}", nRows));

Console.Out.WriteLine("Closing connection");
conn.Close();

Console.WriteLine("Press RETURN to exit");


Console.ReadLine();
}
}
}

Delete data
Use the following code to connect and delete data using a DELETE SQL statement.
The code uses NpgsqlCommand class with method Open() to establish a connection to the PostgreSQL database.
Then, the code uses the CreateCommand() method, sets the CommandText property, and calls the method
ExecuteNonQuery() to run the database commands.
Replace the Host, DBName, User, and Password parameters with the values that you specified when you created
the server and database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;

namespace Driver
{
public class AzurePostgresDelete
{
// Obtain connection string information from the portal
//
private static string Host = "mydemoserver.postgres.database.azure.com";
private static string User = "mylogin@mydemoserver";
private static string DBname = "mypgsqldb";
private static string Password = "<server_admin_password>";
private static string Port = "5432";

static void Main(string[] args)


{
// Build connection string using parameters from portal
//
string connString =
String.Format(
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};",
Host,
User,
DBname,
Port,
Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection");
conn.Open();

var command = conn.CreateCommand();


command.CommandText =
String.Format("DELETE FROM inventory WHERE name = {0};",
"\'orange\'");
int nRows = command.ExecuteNonQuery();
Console.Out.WriteLine(String.Format("Number of rows deleted={0}", nRows));

Console.Out.WriteLine("Closing connection");
conn.Close();

Console.WriteLine("Press RETURN to exit");


Console.ReadLine();
}
}
}

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Go language to
connect and query data
5/21/2018 • 8 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using code written in the Go
language (golang). It shows how to use SQL statements to query, insert, update, and delete data in the database.
This article assumes you are familiar with development using Go, but that you are new to working with Azure
Database for PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - Azure CLI

Install Go and pq connector


Install Go and the Pure Go Postgres driver (pq) on your own machine. Depending on your platform, follow the
appropriate steps:
Windows
1. Download and install Go for Microsoft Windows according to the installation instructions.
2. Launch the command prompt from the start menu.
3. Make a folder for your project, such as mkdir %USERPROFILE%\go\src\postgresqlgo .
4. Change directory into the project folder, such as cd %USERPROFILE%\go\src\postgresqlgo .
5. Set the environment variable for GOPATH to point to the source code directory. set GOPATH=%USERPROFILE%\go .
6. Install the Pure Go Postgres driver (pq) by running the go get github.com/lib/pq command.
In summary, install Go, then run these commands in the command prompt:

mkdir %USERPROFILE%\go\src\postgresqlgo
cd %USERPROFILE%\go\src\postgresqlgo
set GOPATH=%USERPROFILE%\go
go get github.com/lib/pq

Linux (Ubuntu)
1. Launch the Bash shell.
2. Install Go by running sudo apt-get install golang-go .
3. Make a folder for your project in your home directory, such as mkdir -p ~/go/src/postgresqlgo/ .
4. Change directory into the folder, such as cd ~/go/src/postgresqlgo/ .
5. Set the GOPATH environment variable to point to a valid source directory, such as your current home
directory's go folder. At the bash shell, run export GOPATH=~/go to add the go directory as the GOPATH for the
current shell session.
6. Install the Pure Go Postgres driver (pq) by running the go get github.com/lib/pq command.
In summary, run these bash commands:
sudo apt-get install golang-go
mkdir -p ~/go/src/postgresqlgo/
cd ~/go/src/postgresqlgo/
export GOPATH=~/go/
go get github.com/lib/pq

Apple macOS
1. Download and install Go according to the installation instructions matching your platform.
2. Launch the Bash shell.
3. Make a folder for your project in your home directory, such as mkdir -p ~/go/src/postgresqlgo/ .
4. Change directory into the folder, such as cd ~/go/src/postgresqlgo/ .
5. Set the GOPATH environment variable to point to a valid source directory, such as your current home
directory's go folder. At the bash shell, run export GOPATH=~/go to add the go directory as the GOPATH for the
current shell session.
6. Install the Pure Go Postgres driver (pq) by running the go get github.com/lib/pq command.
In summary, install Go, then run these bash commands:

mkdir -p ~/go/src/postgresqlgo/
cd ~/go/src/postgresqlgo/
export GOPATH=~/go/
go get github.com/lib/pq

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created
(such as mydemoserver).
3. Click the server name.
4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you
forget your password, you can also reset the password from this panel.

Build and run Go code


1. To write Golang code, you can use a plain text editor, such as Notepad in Microsoft Windows, vi or Nano in
Ubuntu, or TextEdit in macOS. If you prefer a richer Interactive Development Environment (IDE ) try Gogland by
Jetbrains, Visual Studio Code by Microsoft, or Atom.
2. Paste the Golang code from the following sections into text files, and save into your project folder with file
extension *.go, such as Windows path %USERPROFILE%\go\src\postgresqlgo\createtable.go or Linux path
~/go/src/postgresqlgo/createtable.go .
3. Locate the HOST , DATABASE , USER , and PASSWORD constants in the code, and replace the example values with
your own values.
4. Launch the command prompt or bash shell. Change directory into your project folder. For example, on
Windows cd %USERPROFILE%\go\src\postgresqlgo\ . On Linux cd ~/go/src/postgresqlgo/ . Some of the IDE
environments mentioned offer debug and runtime capabilities without requiring shell commands.
5. Run the code by typing the command go run createtable.go to compile the application and run it.
6. Alternatively, to build the code into a native application, go build createtable.go , then launch createtable.exe
to run the application.

Connect and create a table


Use the following code to connect and create a table using CREATE TABLE SQL statement, followed by INSERT
INTO SQL statements to add rows into the table.
The code imports three packages: the sql package, the pq package as a driver to communicate with the
PostgreSQL server, and the fmt package for printed input and output on the command line.
The code calls method sql.Open() to connect to Azure Database for PostgreSQL database, and checks the
connection using method db.Ping(). A database handle is used throughout, holding the connection pool for the
database server. The code calls the Exec() method several times to run several SQL commands. Each time a custom
checkError() method checks if an error occurred and panic to exit if an error does occur.
Replace the HOST , DATABASE , USER , and PASSWORD parameters with your own values.
package main

import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)

const (
// Initialize connection constants.
HOST = "mydemoserver.postgres.database.azure.com"
DATABASE = "mypgsqldb"
USER = "mylogin@mydemoserver"
PASSWORD = "<server_admin_password>"
)

func checkError(err error) {


if err != nil {
panic(err)
}
}

func main() {
// Initialize connection string.
var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST,
USER, PASSWORD, DATABASE)

// Initialize connection object.


db, err := sql.Open("postgres", connectionString)
checkError(err)

err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")

// Drop previous table of same name if one exists.


_, err = db.Exec("DROP TABLE IF EXISTS inventory;")
checkError(err)
fmt.Println("Finished dropping table (if existed)")

// Create table.
_, err = db.Exec("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
checkError(err)
fmt.Println("Finished creating table")

// Insert some data into table.


sql_statement := "INSERT INTO inventory (name, quantity) VALUES ($1, $2);"
_, err = db.Exec(sql_statement, "banana", 150)
checkError(err)
_, err = db.Exec(sql_statement, "orange", 154)
checkError(err)
_, err = db.Exec(sql_statement, "apple", 100)
checkError(err)
fmt.Println("Inserted 3 rows of data")
}

Read data
Use the following code to connect and read the data using a SELECT SQL statement.
The code imports three packages: the sql package, the pq package as a driver to communicate with the
PostgreSQL server, and the fmt package for printed input and output on the command line.
The code calls method sql.Open() to connect to Azure Database for PostgreSQL database, and checks the
connection using method db.Ping(). A database handle is used throughout, holding the connection pool for the
database server. The select query is run by calling method db.Query(), and the resulting rows are kept in a variable
of type rows. The code reads the column data values in the current row using method rows.Scan() and loops over
the rows using the iterator rows.Next() until no more rows exist. Each row's column values are printed to the
console out. Each time a custom checkError() method is used to check if an error occurred and panic to exit if an
error does occur.
Replace the HOST , DATABASE , USER , and PASSWORD parameters with your own values.

package main

import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)

const (
// Initialize connection constants.
HOST = "mydemoserver.postgres.database.azure.com"
DATABASE = "mypgsqldb"
USER = "mylogin@mydemoserver"
PASSWORD = "<server_admin_password>"
)

func checkError(err error) {


if err != nil {
panic(err)
}
}

func main() {

// Initialize connection string.


var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST,
USER, PASSWORD, DATABASE)

// Initialize connection object.


db, err := sql.Open("postgres", connectionString)
checkError(err)

err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")

// Read rows from table.


var id int
var name string
var quantity int

sql_statement := "SELECT * from inventory;"


rows, err := db.Query(sql_statement)
checkError(err)
defer rows.Close()

for rows.Next() {
switch err := rows.Scan(&id, &name, &quantity); err {
case sql.ErrNoRows:
fmt.Println("No rows were returned")
case nil:
fmt.Printf("Data row = (%d, %s, %d)\n", id, name, quantity)
default:
checkError(err)
}
}
}
Update data
Use the following code to connect and update the data using an UPDATE SQL statement.
The code imports three packages: the sql package, the pq package as a driver to communicate with the Postgres
server, and the fmt package for printed input and output on the command line.
The code calls method sql.Open() to connect to Azure Database for PostgreSQL database, and checks the
connection using method db.Ping(). A database handle is used throughout, holding the connection pool for the
database server. The code calls the Exec() method to run the SQL statement that updates the table. A custom
checkError() method is used to check if an error occurred and panic to exit if an error does occur.
Replace the HOST , DATABASE , USER , and PASSWORD parameters with your own values.

package main

import (
"database/sql"
_ "github.com/lib/pq"
"fmt"
)

const (
// Initialize connection constants.
HOST = "mydemoserver.postgres.database.azure.com"
DATABASE = "mypgsqldb"
USER = "mylogin@mydemoserver"
PASSWORD = "<server_admin_password>"
)

func checkError(err error) {


if err != nil {
panic(err)
}
}

func main() {

// Initialize connection string.


var connectionString string =
fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST, USER, PASSWORD, DATABASE)

// Initialize connection object.


db, err := sql.Open("postgres", connectionString)
checkError(err)

err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")

// Modify some data in table.


sql_statement := "UPDATE inventory SET quantity = $2 WHERE name = $1;"
_, err = db.Exec(sql_statement, "banana", 200)
checkError(err)
fmt.Println("Updated 1 row of data")
}

Delete data
Use the following code to connect and delete the data using a DELETE SQL statement.
The code imports three packages: the sql package, the pq package as a driver to communicate with the Postgres
server, and the fmt package for printed input and output on the command line.
The code calls method sql.Open() to connect to Azure Database for PostgreSQL database, and checks the
connection using method db.Ping(). A database handle is used throughout, holding the connection pool for the
database server. The code calls the Exec() method to run the SQL statement that deletes a row from the table. A
custom checkError() method is used to check if an error occurred and panic to exit if an error does occur.
Replace the HOST , DATABASE , USER , and PASSWORD parameters with your own values.

package main

import (
"database/sql"
_ "github.com/lib/pq"
"fmt"
)

const (
// Initialize connection constants.
HOST = "mydemoserver.postgres.database.azure.com"
DATABASE = "mypgsqldb"
USER = "mylogin@mydemoserver"
PASSWORD = "<server_admin_password>"
)

func checkError(err error) {


if err != nil {
panic(err)
}
}

func main() {

// Initialize connection string.


var connectionString string =
fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST, USER, PASSWORD, DATABASE)

// Initialize connection object.


db, err := sql.Open("postgres", connectionString)
checkError(err)

err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")

// Delete some data from table.


sql_statement := "DELETE FROM inventory WHERE name = $1;"
_, err = db.Exec(sql_statement, "orange")
checkError(err)
fmt.Println("Deleted 1 row of data")
}

Next steps
Migrate your database using Export and Import
Tutorial: Design an Azure Database for PostgreSQL
using the Azure portal
3/20/2018 • 6 minutes to read • Edit Online

Azure Database for PostgreSQL is a managed service that enables you to run, manage, and scale highly available
PostgreSQL databases in the cloud. Using the Azure portal, you can easily manage your server and design a
database.
In this tutorial, you use the Azure portal to learn how to:
Create an Azure Database for PostgreSQL server
Configure the server firewall
Use psql utility to create a database
Load sample data
Query data
Update data
Restore data

Prerequisites
If you don't have an Azure subscription, create a free account before you begin.

Log in to the Azure portal


Log in to the Azure portal.

Create an Azure Database for PostgreSQL


An Azure Database for PostgreSQL server is created with a defined set of compute and storage resources. The
server is created within an Azure resource group.
Follow these steps to create an Azure Database for PostgreSQL server:
1. Click Create a resource in the upper left-hand corner of the Azure portal.
2. Select Databases from the New page, and select Azure Database for PostgreSQL from the Databases
page.
3. Fill out the new server details form with the following information:
Server name: mydemoserver (name of a server maps to DNS name and is thus required to be globally
unique)
Subscription: If you have multiple subscriptions, choose the appropriate subscription in which the
resource exists or is billed for.
Resource group: myresourcegroup
Server admin login and password of your choice
Location
PostgreSQL Version

IMPORTANT
The server admin login and password that you specify here are required to log in to the server and its databases later
in this tutorial. Remember or record this information for later use.

4. Click Pricing tier to specify the pricing tier for your new server. For this tutorial, select General Purpose,
Gen 4 compute generation, 2 vCores, 5 GB of storage and 7 days backup retention period. Select the
Geographically Redundant backup redundancy option to have your server's automatic backups stored in
geo-redundant storage.
5. Click Ok.
6. Click Create to provision the server. Provisioning takes a few minutes.
7. On the toolbar, click Notifications to monitor the deployment process.

TIP
Check the Pin to dashboard option to allow easy tracking of your deployments.

By default, postgres database gets created under your server. The postgres database is a default database
meant for use by users, utilities, and third-party applications.

Configure a server-level firewall rule


The Azure Database for PostgreSQL service uses a firewall at the server-level. By default, this firewall prevents all
external applications and tools from connecting to the server and any databases on the server unless a firewall rule
is created to open the firewall for a specific IP address range.
1. After the deployment completes, click All Resources from the left-hand menu and type in the name
mydemoserver to search for your newly created server. Click the server name listed in the search result.
The Overview page for your server opens and provides options for further configuration.
2. In the server page, select Connection security.
3. Click in the text box under Rule Name, and add a new firewall rule to whitelist the IP range for connectivity.
For this tutorial, let's allow all IPs by typing in Rule Name = AllowAllIps, Start IP = 0.0.0.0 and End IP =
255.255.255.255 and then click Save. You can set a specific firewall rule that covers a smaller IP range to be
able to connect from your network.

4. Click Save and then click the X to close the Connections security page.

NOTE
Azure PostgreSQL server communicates over port 5432. If you are trying to connect from within a corporate
network, outbound traffic over port 5432 may not be allowed by your network's firewall. If so, you cannot connect to
your Azure SQL Database server unless your IT department opens port 5432.

Get the connection information


When you created the Azure Database for PostgreSQL server, the default postgres database was also created. To
connect to your database server, you need to provide host information and access credentials.
1. From the left-hand menu in the Azure portal, click All resources and search for the server you just created.

2. Click the server name mydemoserver.


3. Select the server's Overview page. Make a note of the Server name and Server admin login name.

Connect to PostgreSQL database using psql in Cloud Shell


Let's now use the psql command-line utility to connect to the Azure Database for PostgreSQL server.
1. Launch the Azure Cloud Shell via the terminal icon on the top navigation pane.

2. The Azure Cloud Shell opens in your browser, enabling you to type bash commands.

3. At the Cloud Shell prompt, connect to your Azure Database for PostgreSQL server using the psql
commands. The following format is used to connect to an Azure Database for PostgreSQL server with the
psql utility:

psql --host=<myserver> --port=<port> --username=<server admin login> --dbname=<database name>


For example, the following command connects to the default database called postgres on your PostgreSQL
server mydemoserver.postgres.database.azure.com using access credentials. Enter your server admin
password when prompted.

psql --host=mydemoserver.postgres.database.azure.com --port=5432 --username=myadmin@mydemoserver --


dbname=postgres

Create a new database


Once you're connected to the server, create a blank database at the prompt.

CREATE DATABASE mypgsqldb;

At the prompt, execute the following command to switch connection to the newly created database mypgsqldb.

\c mypgsqldb

Create tables in the database


Now that you know how to connect to the Azure Database for PostgreSQL, you can complete some basic tasks:
First, create a table and load it with some data. Let's create a table that tracks inventory information using this SQL
code:

CREATE TABLE inventory (


id serial PRIMARY KEY,
name VARCHAR(50),
quantity INTEGER
);

You can see the newly created table in the list of tables now by typing:

\dt

Load data into the tables


Now that you have a table, insert some data into it. At the open command prompt window, run the following
query to insert some rows of data.

INSERT INTO inventory (id, name, quantity) VALUES (1, 'banana', 150);
INSERT INTO inventory (id, name, quantity) VALUES (2, 'orange', 154);

You have now two rows of sample data into the inventory table you created earlier.

Query and update the data in the tables


Execute the following query to retrieve information from the inventory database table.

SELECT * FROM inventory;


You can also update the data in the table.

UPDATE inventory SET quantity = 200 WHERE name = 'banana';

You can see the updated values when you retrieve the data.

SELECT * FROM inventory;

Restore data to a previous point in time


Imagine you have accidentally deleted this table. This situation is something you cannot easily recover from. Azure
Database for PostgreSQL allows you to go back to any point-in-time for which your server has backups
(determined by the backup retention period you configured) and restore this point-in-time to a new server. You can
use this new server to recover your deleted data. The following steps restore the mydemoserver server to a point
before the inventory table was added.
1. On the Azure Database for PostgreSQL Overview page for your server, click Restore on the toolbar. The
Restore page opens.

2. Fill out the Restore form with the required information:

Restore point: Select a point-in-time that occurs before the server was changed
Target server: Provide a new server name you want to restore to
Location: You cannot select the region, by default it is same as the source server
Pricing tier: You cannot change this value when restoring a server. It is same as the source server.
3. Click OK to restore the server to a point-in-time before the table was deleted. Restoring a server to a different
point in time creates a duplicate new server as the original server as of the point in time you specify, provided
that it is within the retention period for your pricing tier.

Next steps
In this tutorial, you learned how to use the Azure portal and other utilities to:
Create an Azure Database for PostgreSQL server
Configure the server firewall
Use psql utility to create a database
Load sample data
Query data
Update data
Restore data
Next, to learn how to use the Azure CLI to do similar tasks, review this tutorial: Design your first Azure Database
for PostgreSQL using Azure CLI
Tutorial: Design an Azure Database for PostgreSQL
using Azure CLI
6/27/2018 • 7 minutes to read • Edit Online

In this tutorial, you use Azure CLI (command-line interface) and other utilities to learn how to:
Create an Azure Database for PostgreSQL server
Configure the server firewall
Use psql utility to create a database
Load sample data
Query data
Update data
Restore data
You may use the Azure Cloud Shell in the browser, or install Azure CLI 2.0 on your own computer to run the
commands in this tutorial.

Open Azure Cloud Shell


Azure Cloud Shell is a free, interactive shell that you can use to run the steps in this article. Common Azure tools
are preinstalled and configured in Cloud Shell for you to use with your account. Just select the Copy button to
copy the code, paste it in Cloud Shell, and then press Enter to run it. There are a few ways to open Cloud Shell:

Select Try It in the upper-right corner of a code block.

Open Cloud Shell in your browser.

Select the Cloud Shell button on the menu in the upper-right


corner of the Azure portal.

If you choose to install and use the CLI locally, this article requires that you are running the Azure CLI version 2.0
or later. Run az --version to find the version. If you need to install or upgrade, see Install Azure CLI 2.0.
If you have multiple subscriptions, choose the appropriate subscription in which the resource exists or is billed for.
Select a specific subscription ID under your account using az account set command.

az account set --subscription 00000000-0000-0000-0000-000000000000

Create a resource group


Create an Azure resource group using the az group create command. A resource group is a logical container into
which Azure resources are deployed and managed as a group. The following example creates a resource group
named myresourcegroup in the westus location.
az group create --name myresourcegroup --location westus

Create an Azure Database for PostgreSQL server


Create an Azure Database for PostgreSQL server using the az postgres server create command. A server contains
a group of databases managed as a group.
The following example creates a server called mydemoserver in your resource group myresourcegroup with server
admin login myadmin . The name of a server maps to DNS name and is thus required to be globally unique in
Azure. Substitute the <server_admin_password> with your own value. It is a General Purpose, Gen 4 server with 2
vCores.

az postgres server create --resource-group myresourcegroup --name mydemoserver --location westus --admin-user
myadmin --admin-password <server_admin_password> --sku-name GP_Gen4_2 --version 9.6

The sku-name parameter value follows the convention {pricing tier}_{compute generation}_{vCores} as in the
examples below:
--sku-name B_Gen4_4 maps to Basic, Gen 4, and 4 vCores.
--sku-name GP_Gen5_32 maps to General Purpose, Gen 5, and 32 vCores.
--sku-name MO_Gen5_2 maps to Memory Optimized, Gen 5, and 2 vCores.

Please see the pricing tiers documentation to understand the valid values per region and per tier.

IMPORTANT
The server admin login and password that you specify here are required to log in to the server and its databases later in this
quickstart. Remember or record this information for later use.

By default, postgres database gets created under your server. The postgres database is a default database meant
for use by users, utilities, and third-party applications.

Configure a server-level firewall rule


Create an Azure PostgreSQL server-level firewall rule with the az postgres server firewall-rule create command. A
server-level firewall rule allows an external application, such as psql or PgAdmin to connect to your server through
the Azure PostgreSQL service firewall.
You can set a firewall rule that covers an IP range to be able to connect from your network. The following example
uses az postgres server firewall-rule create to create a firewall rule AllowMyIP that allows connection from a single
IP address.

az postgres server firewall-rule create --resource-group myresourcegroup --server mydemoserver --name


AllowMyIP --start-ip-address 192.168.0.1 --end-ip-address 192.168.0.1

To restrict access to your Azure PostgreSQL server to only your network, you can set the firewall rule to only cover
your corporate network IP address range.
NOTE
Azure PostgreSQL server communicates over port 5432. When connecting from within a corporate network, outbound traffic
over port 5432 may not be allowed by your network's firewall. Have your IT department open port 5432 to connect to your
Azure SQL Database server.

Get the connection information


To connect to your server, you need to provide host information and access credentials.

az postgres server show --resource-group myresourcegroup --name mydemoserver

The result is in JSON format. Make a note of the administratorLogin and fullyQualifiedDomainName.

{
"administratorLogin": "myadmin",
"earliestRestoreDate": null,
"fullyQualifiedDomainName": "mydemoserver.postgres.database.azure.com",
"id": "/subscriptions/00000000-0000-0000-0000-
000000000000/resourceGroups/myresourcegroup/providers/Microsoft.DBforPostgreSQL/servers/mydemoserver",
"location": "westus",
"name": "mydemoserver",
"resourceGroup": "myresourcegroup",
"sku": {
"capacity": 2,
"family": "Gen4",
"name": "GP_Gen4_2",
"size": null,
"tier": "GeneralPurpose"
},
"sslEnforcement": "Enabled",
"storageProfile": {
"backupRetentionDays": 7,
"geoRedundantBackup": "Disabled",
"storageMb": 5120
},
"tags": null,
"type": "Microsoft.DBforPostgreSQL/servers",
"userVisibleState": "Ready",
"version": "9.6"

Connect to Azure Database for PostgreSQL database using psql


If your client computer has PostgreSQL installed, you can use a local instance of psql, or the Azure Cloud Console
to connect to an Azure PostgreSQL server. Let's now use the psql command-line utility to connect to the Azure
Database for PostgreSQL server.
1. Run the following psql command to connect to an Azure Database for PostgreSQL database:

psql --host=<servername> --port=<port> --username=<user@servername> --dbname=<dbname>

For example, the following command connects to the default database called postgres on your PostgreSQL
server mydemoserver.postgres.database.azure.com using access credentials. Enter the
<server_admin_password> you chose when prompted for password.
psql --host=mydemoserver.postgres.database.azure.com --port=5432 --username=myadmin@mydemoserver --
dbname=postgres

2. Once you are connected to the server, create a blank database at the prompt:

CREATE DATABASE mypgsqldb;

3. At the prompt, execute the following command to switch connection to the newly created database
mypgsqldb:

\c mypgsqldb

Create tables in the database


Now that you know how to connect to the Azure Database for PostgreSQL, you can complete some basic tasks:
First, create a table and load it with some data. For example, create a table that tracks inventory information:

CREATE TABLE inventory (


id serial PRIMARY KEY,
name VARCHAR(50),
quantity INTEGER
);

You can see the newly created table in the list of tables now by typing:

\dt

Load data into the table


Now that there is a table created, insert some data into it. At the open command prompt window, run the following
query to insert some rows of data:

INSERT INTO inventory (id, name, quantity) VALUES (1, 'banana', 150);
INSERT INTO inventory (id, name, quantity) VALUES (2, 'orange', 154);

You have now added two rows of sample data into the table you created earlier.

Query and update the data in the tables


Execute the following query to retrieve information from the inventory table:

SELECT * FROM inventory;

You can also update the data in the inventory table:

UPDATE inventory SET quantity = 200 WHERE name = 'banana';

You can see the updated values when you retrieve the data:
SELECT * FROM inventory;

Restore a database to a previous point in time


Imagine you have accidentally deleted a table. This is something you cannot easily recover from. Azure Database
for PostgreSQL allows you to go back to any point-in-time for which your server has backups (determined by the
backup retention period you configured) and restore this point-in-time to a new server. You can use this new server
to recover your deleted data.
The following command restores the sample server to a point before the table was added:

az postgres server restore --resource-group myresourcegroup --name mydemoserver-restored --restore-point-in-


time 2017-04-13T13:59:00Z --source-server mydemoserver

The az postgres server restore command needs the following parameters:

SETTING SUGGESTED VALUE DESCRIPTION

resource-group myresourcegroup The resource group in which the source


server exists.

name mydemoserver-restored The name of the new server that is


created by the restore command.

restore-point-in-time 2017-04-13T13:59:00Z Select a point-in-time to restore to. This


date and time must be within the
source server's backup retention period.
Use ISO8601 date and time format. For
example, you may use your own local
timezone, such as
2017-04-13T05:59:00-08:00 , or use
UTC Zulu format
2017-04-13T13:59:00Z .

source-server mydemoserver The name or ID of the source server to


restore from.

Restoring a server to a point-in-time creates a new server, copied as the original server as of the point in time you
specify. The location and pricing tier values for the restored server are the same as the source server.
The command is synchronous, and will return after the server is restored. Once the restore finishes, locate the new
server that was created. Verify the data was restored as expected.

Next steps
In this tutorial, you learned how to use Azure CLI (command-line interface) and other utilities to:
Create an Azure Database for PostgreSQL server
Configure the server firewall
Use psql utility to create a database
Load sample data
Query data
Update data
Restore data
Next, learn how to use the Azure portal to do similar tasks, review this tutorial: Design your first Azure Database
for PostgreSQL using the Azure portal
2 minutes to read
Azure CLI samples for Azure Database for
PostgreSQL
2/27/2018 • 2 minutes to read • Edit Online

The following table includes links to sample Azure CLI scripts for Azure Database for PostgreSQL.

Create a server

Create a server and firewall rule Azure CLI script that creates an Azure Database for
PostgreSQL server and configures a server-level firewall rule.

Scale a server

Scale a server Azure CLI script that scales an Azure Database for PostgreSQL
server up or down to allow for changing performance needs.

Change server configurations

Change server configurations Azure CLI script that change configurations options of an
Azure Database for PostgreSQL server.

Restore a server

Restore a server Azure CLI script that restores an Azure Database for
PostgreSQL server to a previous point in time.

Download server logs

Enable and download server logs Azure CLI script that enables and downloads server logs of an
Azure Database for PostgreSQL server.
Azure Database for PostgreSQL servers
5/23/2018 • 3 minutes to read • Edit Online

This article provides considerations and guidelines for working with Azure Database for PostgreSQL servers.

What is an Azure Database for PostgreSQL server?


An Azure Database for PostgreSQL server is a central administrative point for multiple databases. It is the same
PostgreSQL server construct that you may be familiar with in the on-premises world. Specifically, the PostgreSQL
service is managed, provides performance guarantees, exposes access and features at the server-level.
An Azure Database for PostgreSQL server:
Is created within an Azure subscription.
Is the parent resource for databases.
Provides a namespace for databases.
Is a container with strong lifetime semantics - delete a server and it deletes the contained databases.
Collocates resources in a region.
Provides a connection endpoint for server and database access (.postgresql.database.azure.com).
Provides the scope for management policies that apply to its databases: login, firewall, users, roles,
configurations, etc.
Is available in multiple versions. For more information, see supported PostgreSQL database versions.
Is extensible by users. For more information, see PostgreSQL extensions.
Within an Azure Database for PostgreSQL server, you can create one or multiple databases. You can opt to create a
single database per server to utilize all the resources, or create multiple databases to share the resources. The
pricing is structured per-server, based on the configuration of pricing tier, vCores, and storage (GB ). For more
information, see Pricing tiers.

How do I connect and authenticate to an Azure Database for


PostgreSQL server?
The following elements help ensure safe access to your database:

Authentication and authorization Azure Database for PostgreSQL server supports native
PostgreSQL authentication. You can connect and authenticate
to server with the server's admin login.

Protocol The service supports a message-based protocol used by


PostgreSQL.

TCP/IP The protocol is supported over TCP/IP, and over Unix-domain


sockets.

Firewall To help protect your data, a firewall rule prevents all access to
your server and to its databases, until you specify which
computers have permission. See Azure Database for
PostgreSQL Server firewall rules.
Managing your server
You can manage Azure Database for PostgreSQL servers by using the Azure portal or the Azure CLI.
While creating a server, you set up the credentials for your admin user. The admin user is the highest privilege user
you have on the server. It belongs to the role azure_pg_admin. This role does not have full superuser permissions.
The PostgreSQL superuser attribute is assigned to the azure_superuser, which belongs to the managed service.
You do not have access to this role.
An Azure Database for PostgreSQL server has two default databases:
postgres - A default database you can connect to once your server is created.
azure_maintenance - This database is used to separate the processes that provide the managed service from
user actions. You do not have access to this database.

Server parameters
The PostgreSQL server parameters determine the configuration of the server. In Azure Database for PostgreSQL,
the list of parameters can be viewed and edited using the Azure portal or the Azure CLI.
As a managed service for Postgres, the configurable parameters in Azure Database for PostgreSQL are a subset of
the parameters in a local Postgres instance (For more information on Postgres parameters, see the PostgreSQL
documentation). Your Azure Database for PostgreSQL server is enabled with default values for each parameter on
creation. Some parameters that would require a server restart or superuser access for changes to take effect
cannot be configured by the user.

Next steps
For an overview of the service, see Azure Database for PostgreSQL Overview.
For information about specific resource quotas and limitations based on your service tier, see Service tiers.
For information on connecting to the service, see Connection libraries for Azure Database for PostgreSQL.
View and edit server parameters through Azure portal or Azure CLI.
Supported PostgreSQL Database Versions
6/1/2018 • 2 minutes to read • Edit Online

Microsoft aims to support n-2 versions of the PostgreSQL engine in the Azure Database for PostgreSQL service,
meaning the currently released major version (n) and the two prior major versions (-2).
Azure Database for PostgreSQL currently supports the following versions:

PostgreSQL Version 10.3


Refer to the PostgreSQL documentation to learn more about improvements and fixes in PostgreSQL 10.3.

PostgreSQL Version 9.6.7


Refer to the PostgreSQL documentation to learn more about improvements and fixes in PostgreSQL 9.6.7.

PostgreSQL Version 9.5.11


Refer to the PostgreSQL documentation to learn about improvements and fixes in PostgreSQL 9.5.11.

Managing updates and upgrades


Azure Database for PostgreSQL automatically manages patching for minor version updates. Currently, major
version upgrade is not supported. For example, upgrading from PostgreSQL 9.5 to PostgreSQL 9.6 is not
supported.

Next steps
For information about the support of different PostgreSQL extensions, see PostgreSQL Extensions.
PostgreSQL extensions in Azure Database for
PostgreSQL
7/11/2018 • 3 minutes to read • Edit Online

PostgreSQL provides the ability to extend the functionality of your database using extensions. Extensions allow for
bundling multiple related SQL objects together in a single package that can be loaded or removed from your
database with a single command. After being loaded in the database, extensions can function as do built-in
features. For more information on PostgreSQL extensions, see Packaging Related Objects into an Extension.

How to use PostgreSQL extensions


PostgreSQL extensions must be installed in your database before you can use them. To install a particular
extension, run the CREATE EXTENSION command from psql tool to load the packaged objects into your
database.
Azure Database for PostgreSQL currently supports a subset of key extensions as listed below. Extensions beyond
the ones listed are not supported; you cannot create your own extension with Azure Database for PostgreSQL
service.

Extensions supported by Azure Database for PostgreSQL


The following tables list the standard PostgreSQL extensions that are currently supported by Azure Database for
PostgreSQL. This information is also available by running SELECT * FROM pg_available_extensions; .
Data types extensions
EX TENSION DESCRIPTION

chkpass Provides a data type for auto-encrypted passwords.

citext Provides a case-insensitive character string type.

cube Provides a data type for multidimensional cubes.

hstore Provides a data type for storing sets of key/value pairs.

isn Provides data types for international product numbering


standards.

ltree Provides a data type for hierarchical tree-like structures.

Functions extensions
EX TENSION DESCRIPTION

earthdistance Provides a means to calculate great-circle distances on the


surface of the Earth.

fuzzystrmatch Provides several functions to determine similarities and


distance between strings.
EX TENSION DESCRIPTION

intarray Provides functions and operators for manipulating null-free


arrays of integers.

pgcrypto Provides cryptographic functions.

pg_partman Manages partitioned tables by time or ID.

pg_trgm Provides functions and operators for determining the


similarity of alphanumeric text based on trigram matching.

tablefunc Provides functions that manipulate whole tables, including


crosstab.

uuid-ossp Generates universally unique identifiers (UUIDs).

Full-text search extensions


EX TENSION DESCRIPTION

dict_int Provides a text search dictionary template for integers.

unaccent A text search dictionary that removes accents (diacritic signs)


from lexemes.

Index Types extensions


EX TENSION DESCRIPTION

btree_gin Provides sample GIN operator classes that implement B-tree


like behavior for certain data types.

btree_gist Provides GiST index operator classes that implement B-tree.

Language extensions
EX TENSION DESCRIPTION

plpgsql PL/pgSQL loadable procedural language.

Miscellaneous extensions
EX TENSION DESCRIPTION

pg_buffercache Provides a means for examining what's happening in the


shared buffer cache in real time.

pg_prewarm Provides a way to load relation data into the buffer cache.

pg_stat_statements Provides a means for tracking execution statistics of all SQL


statements executed by a server. (See below for a note on this
extension).

pgrowlocks Provides a means for showing row-level locking information.


EX TENSION DESCRIPTION

pgstattuple Provides a means for showing tuple-level statistics.

postgres_fdw Foreign-data wrapper used to access data stored in external


PostgreSQL servers.

hypopg Provides a means of creating hypothetical indexes that don't


cost CPU or disk.

PostGIS extensions
EX TENSION DESCRIPTION

PostGIS, postgis_topology, postgis_tiger_geocoder, Spatial and geographic objects for PostgreSQL.


postgis_sfcgal

address_standardizer, address_standardizer_data_us Used to parse an address into constituent elements. Used to


support geocoding address normalization step.

pgrouting Extends the PostGIS / PostgreSQL geospatial database to


provide geospatial routing functionality.

Using pg_stat_statements
The pg_stat_statements extension is preloaded on every Azure Database for PostgreSQL server to provide you a
means of tracking execution statistics of SQL statements. The setting pg_stat_statements.track , which controls
what statements are counted by the extension, defaults to top , meaning all statements issued directly by clients
are tracked. The two other tracking levels are none and all . This setting is configurable as a server parameter
through the Azure portal or the Azure CLI.
There is a tradeoff between the query execution information pg_stat_statements provides and the impact on
server performance as it logs each SQL statement. If you are not actively using the pg_stat_statements extension,
we recommend that you set pg_stat_statements.track to none . Note that some third party monitoring services
may rely on pg_stat_statements to deliver query performance insights, so confirm whether this is the case for you
or not.

Next steps
If you don't see an extension that you'd like to use, let us know. Vote for existing requests or create new feedback
and requests in our Customer feedback forum.
Server Logs in Azure Database for PostgreSQL
7/3/2018 • 2 minutes to read • Edit Online

Azure Database for PostgreSQL generates query and error logs. However, access to transaction logs is not
supported. Query and error logs can be used to identify, troubleshoot, and repair configuration errors and
suboptimal performance. For more information, see Error Reporting and Logging.

Access server logs


You can list and download Azure PostgreSQL server error logs using the Azure portal, Azure CLI, and Azure REST
APIs.

Log retention
You can set the retention period for system logs using the log_retention_period parameter associated with your
server. The unit for this parameter is days. The default value is 3 days. The maximum value is 7 days. Your server
must have enough allocated storage to contain the retained log files. The log files rotate every one hour or 100
MB size, whichever comes first.

Configure logging for Azure PostgreSQL server


You can enable query logging and error logging for your server. Error logs can contain auto-vacuum, connection,
and checkpoints information.
You can enable query logging for your PostgreSQL DB instance by setting two server parameters: log_statement
and log_min_duration_statement .
The log_statement parameter controls which SQL statements are logged. We recommend setting this parameter
to all to log all statements; the default value is none.
The log_min_duration_statement parameter sets the limit in milliseconds of a statement to be logged. All SQL
statements that run longer than the parameter setting are logged. This parameter is disabled and set to minus 1 (-
1) by default. Enabling this parameter can be helpful in tracking down unoptimized queries in your applications.
The log_min_messages allows you to control which message levels are written to the server log. The default is
WARNING.
For more information on these settings, see Error Reporting and Logging documentation. For particularly
configuring Azure Database for PostgreSQL server parameters, see Customize server configuration parameters
using Azure CLI.

Next steps
To access logs using Azure CLI command-line interface, see Configure and access server logs using Azure CLI.
For more information on server parameters, see Customize server configuration parameters using Azure CLI.
High availability concepts in Azure Database for
PostgreSQL
2/27/2018 • 2 minutes to read • Edit Online

The Azure Database for PostgreSQL service provides a guaranteed high level of availability. The financially backed
service level agreement (SL A) is 99.99% upon general availability. There is virtually no application down time
when using this service.

High availability
The high availability (HA) model is based on built-in fail-over mechanisms when a node-level interruption occurs. A
node-level interruption could occur because of a hardware failure or in response to a service deployment.
At all times, changes made to an Azure Database for PostgreSQL database server occur in the context of a
transaction. Changes are recorded synchronously in Azure storage when the transaction is committed. If a node-
level interruption occurs, the database server automatically creates a new node and attaches data storage to the
new node. Any active connections are dropped and any inflight transactions are not committed.

Application retry logic is essential


It is important that PostgreSQL database applications are built to detect and retry dropped connections and failed
transactions. When the application retries, the application's connection is transparently redirected to the newly
created instance, which takes over for the failed instance.
Internally in Azure, a gateway is used to redirect the connections to the new instance. Upon an interruption, the
entire fail-over process typically takes tens of seconds. Since the redirect is handled internally by the gateway, the
external connection string remains the same for the client applications.

Scaling up or down
Similar to the HA model, when an Azure Database for PostgreSQL is scaled up or down, a new server instance
with the specified size is created. The existing data storage is detached from the original instance, and attached to
the new instance.
During the scale operation, an interruption to the database connections occurs. The client applications are
disconnected, and open uncommitted transactions are canceled. Once the client application retries the connection,
or makes a new connection, the gateway directs the connection to the newly sized instance.

Next steps
For an overview of the service, see Azure Database for PostgreSQL Overview
Azure Database for PostgreSQL pricing tiers
7/20/2018 • 6 minutes to read • Edit Online

You can create an Azure Database for PostgreSQL server in one of three different pricing tiers: Basic, General
Purpose, and Memory Optimized. The pricing tiers are differentiated by the amount of compute in vCores that
can be provisioned, memory per vCore, and the storage technology used to store the data. All resources are
provisioned at the PostgreSQL server level. A server can have one or many databases.

BASIC GENERAL PURPOSE MEMORY OPTIMIZED

Compute generation Gen 4, Gen 5 Gen 4, Gen 5 Gen 5

vCores 1, 2 2, 4, 8, 16, 32 2, 4, 8, 16

Memory per vCore 2 GB 5 GB 10 GB

Storage size 5 GB to 1 TB 5 GB to 4 TB 5 GB to 4 TB

Storage type Azure Standard Storage Azure Premium Storage Azure Premium Storage

Database backup retention 7 to 35 days 7 to 35 days 7 to 35 days


period

To choose a pricing tier, use the following table as a starting point.

PRICING TIER TARGET WORKLOADS

Basic Workloads that require light compute and I/O performance.


Examples include servers used for development or testing or
small-scale infrequently used applications.

General Purpose Most business workloads that require balanced compute and
memory with scalable I/O throughput. Examples include
servers for hosting web and mobile apps and other
enterprise applications.

Memory Optimized High-performance database workloads that require in-


memory performance for faster transaction processing and
higher concurrency. Examples include servers for processing
real-time data and high-performance transactional or
analytical apps.

After you create a server, the number of vCores, hardware generation, and pricing tier (except to and from Basic)
can be changed up or down within seconds. You also can independently adjust the amount of storage up and the
backup retention period up or down with no application downtime. You can't change the backup storage type
after a server is created. For more information, see the Scale resources section.

Compute generations and vCores


Compute resources are provided as vCores, which represent the logical CPU of the underlying hardware.
Currently, you can choose from two compute generations, Gen 4 and Gen 5. Gen 4 logical CPUs are based on
Intel E5-2673 v3 (Haswell) 2.4-GHz processors. Gen 5 logical CPUs are based on Intel E5-2673 v4 (Broadwell)
2.3-GHz processors. Gen 4 and Gen 5 are available in the following regions ("X" denotes available).

AZURE REGION GEN 4 GEN 5

Central US X

East US X X

East US 2 X X

North Central US X X

South Central US X X

West US X X

West US 2 X

Canada Central X X

Canada East X X

Brazil South X X

North Europe X X

West Europe X

France Central X

UK West X

UK South X

East Asia X X

Southeast Asia X X

Australia East X

Australia Central X

Australia Central 2 X

Australia Southeast X

Central India X X

West India X X

South India X
AZURE REGION GEN 4 GEN 5

Japan East X X

Japan West X X

Korea Central X

Korea South X

Storage
The storage you provision is the amount of storage capacity available to your Azure Database for PostgreSQL
server. The storage is used for the database files, temporary files, transaction logs, and the PostgreSQL server
logs. The total amount of storage you provision also defines the I/O capacity available to your server.

BASIC GENERAL PURPOSE MEMORY OPTIMIZED

Storage type Azure Standard Storage Azure Premium Storage Azure Premium Storage

Storage size 5 GB to 1 TB 5 GB to 4 TB 5 GB to 4 TB

Storage increment size 1 GB 1 GB 1 GB

IOPS Variable 3 IOPS/GB 3 IOPS/GB


Min 100 IOPS Min 100 IOPS
Max 6000 IOPS Max 6000 IOPS

You can add additional storage capacity during and after the creation of the server. The Basic tier does not
provide an IOPS guarantee. In the General Purpose and Memory Optimized pricing tiers, the IOPS scale with
the provisioned storage size in a 3:1 ratio.
You can monitor your I/O consumption in the Azure portal or by using Azure CLI commands. The relevant
metrics to monitor are storage limit, storage percentage, storage used, and IO percent.
Reaching the storage limit
The server is marked read-only when the amount of free storage reaches less than 5 GB or 5% of provisioned
storage, whichever is less. For example, if you have provisioned 100 GB of storage, and the actual utilization goes
over 95 GB, the server is marked read-only. Alternatively, if you have provisioned 5 GB of storage, the server is
marked read-only when the free storage reaches less than 250 MB.
When the server is set to read-only, all existing sessions are disconnected and uncommitted transactions are
rolled back. Any subsequent write operations and transaction commits fail. All subsequent read queries will work
uninterrupted.
You can either increase the amount of provisioned storage to your server or start a new session in read-write
mode and drop data to reclaim free storage. Running SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE;
sets the current session to read write mode. In order to avoid data corruption, do not perform any write
operations when the server is still in read-only status.
We recommend that you set up an alert to notify you when your server storage is approaching the threshold so
you can avoid getting into the read-only state. For more information, see the documentation on how to set up an
alert.
Backup
The service automatically takes backups of your server. The minimum retention period for backups is seven days.
You can set a retention period of up to 35 days. The retention can be adjusted at any point during the lifetime of
the server. You can choose between locally redundant and geo-redundant backups. Geo-redundant backups also
are stored in the geo-paired region of the region where your server is created. This redundancy provides a level
of protection in the event of a disaster. You also gain the ability to restore your server to any other Azure region
in which the service is available with geo-redundant backups. It's not possible to change between the two backup
storage options after the server is created.

Scale resources
After you create your server, you can independently change the vCores, the hardware generation, the pricing tier
(except to and from Basic), the amount of storage, and the backup retention period. You can't change the backup
storage type after a server is created. The number of vCores can be scaled up or down. The backup retention
period can be scaled up or down from 7 to 35 days. The storage size can only be increased. Scaling of the
resources can be done either through the portal or Azure CLI. For an example of scaling by using Azure CLI, see
Monitor and scale an Azure Database for PostgreSQL server by using Azure CLI.
When you change the number of vCores, the hardware generation, or the pricing tier, a copy of the original
server is created with the new compute allocation. After the new server is up and running, connections are
switched over to the new server. During the moment when the system switches over to the new server, no new
connections can be established, and all uncommitted transactions are rolled back. This window varies, but in
most cases, is less than a minute.
Scaling storage and changing the backup retention period are true online operations. There is no downtime, and
your application isn't affected. As IOPS scale with the size of the provisioned storage, you can increase the IOPS
available to your server by scaling up storage.

Pricing
For the most up-to-date pricing information, see the service pricing page. To see the cost for the configuration
you want, the Azure portal shows the monthly cost on the Pricing tier tab based on the options you select. If
you don't have an Azure subscription, you can use the Azure pricing calculator to get an estimated price. On the
Azure pricing calculator website, select Add items, expand the Databases category, and choose Azure
Database for PostgreSQL to customize the options.

Next steps
Learn how to create a PostgreSQL server in the portal.
Learn how to monitor and scale an Azure Database for PostgreSQL server by using Azure CLI.
Learn about the service limitations.
Limitations in Azure Database for PostgreSQL
7/20/2018 • 2 minutes to read • Edit Online

The following sections describe capacity and functional limits in the database service.

Maximum connections
The maximum number of connections per pricing tier and vCores are as follows:

PRICING TIER VCORE(S) MAX CONNECTIONS

Basic 1 50

Basic 2 100

General Purpose 2 150

General Purpose 4 250

General Purpose 8 480

General Purpose 16 950

General Purpose 32 1500

Memory Optimized 2 150

Memory Optimized 4 250

Memory Optimized 8 480

Memory Optimized 16 950

When connections exceed the limit, you may receive the following error:

FATAL: sorry, too many clients already

The Azure system requires five connections to monitor the Azure Database for PostgreSQL server.

Functional limitations
Scale operations
Dynamic scaling to and from the Basic pricing tiers is currently not supported.
Decreasing server storage size is currently not supported.
Server version upgrades
Automated migration between major database engine versions is currently not supported.
Subscription management
Dynamically moving servers across subscriptions and resource groups is currently not supported.
VNet service endpoints
Support for VNet service endpoints is only for General Purpose and Memory Optimized servers.
Restoring a server
When using the PITR feature, the new server is created with the same pricing tier configurations as the server it
is based on.
The new server created during a restore does not have the firewall rules that existed on the original server.
Firewall rules need to be set up separately for this new server.
Restoring a deleted server is not supported.

Next steps
Understand what’s available in each pricing tier
Learn about Supported PostgreSQL Database Versions
Review how to back up and restore a server in Azure Database for PostgreSQL using the Azure portal
Azure Database for PostgreSQL Server firewall rules
2/27/2018 • 4 minutes to read • Edit Online

Azure Database for PostgreSQL Server firewall prevents all access to your database server until you specify which
computers have permission. The firewall grants access to the server based on the originating IP address of each
request. To configure your firewall, you create firewall rules that specify ranges of acceptable IP addresses. You can
create firewall rules at the server level.
Firewall rules: These rules enable clients to access your entire Azure Database for PostgreSQL Server, that is, all
the databases within the same logical server. Server-level firewall rules can be configured by using the Azure
portal or using Azure CLI commands. To create server-level firewall rules, you must be the subscription owner or a
subscription contributor.

Firewall overview
All database access to your Azure Database for PostgreSQL server is blocked by the firewall by default. To begin
using your server from another computer, you need to specify one or more server-level firewall rules to enable
access to your server. Use the firewall rules to specify which IP address ranges from the Internet to allow. Access to
the Azure portal website itself is not impacted by the firewall rules. Connection attempts from the Internet and
Azure must first pass through the firewall before they can reach your PostgreSQL Database, as shown in the
following diagram:

Connecting from the Internet


Server-level firewall rules apply to all databases on the same Azure Database for PostgreSQL server. If the IP
address of the request is within one of the ranges specified in the server-level firewall rules, the connection is
granted. If the IP address of the request is not within the ranges specified in any of the server-level firewall rules,
the connection request fails. For example, if your application connects with JDBC driver for PostgreSQL, you may
encounter this error attempting to connect when the firewall is blocking the connection.

java.util.concurrent.ExecutionException: java.lang.RuntimeException: org.postgresql.util.PSQLException: FATAL:


no pg_hba.conf entry for host "123.45.67.890", user "adminuser", database "postgresql", SSL

Connecting from Azure


To allow applications from Azure to connect to your Azure Database for PostgreSQL server, Azure connections
must be enabled. For example, to host an Azure Web Apps application, or an application that runs in an Azure VM,
or to connect from an Azure Data Factory data management gateway. The resources do not need to be in the same
Virtual Network (VNet) or Resource Group for the firewall rule to enable those connections. When an application
from Azure attempts to connect to your database server, the firewall verifies that Azure connections are allowed.
There are a couple of methods to enable these types of connections. A firewall setting with starting and ending
address equal to 0.0.0.0 indicates these connections are allowed. Alternatively, you can set the Allow access to
Azure services option to ON in the portal from the Connection security pane and hit save. If the connection
attempt is not allowed, the request does not reach the Azure Database for PostgreSQL server.

IMPORTANT
This option configures the firewall to allow all connections from Azure including connections from the subscriptions of other
customers. When selecting this option, make sure your login and user permissions limit access to only authorized users.

Programmatically managing firewall rules


In addition to the Azure portal, firewall rules can be managed programmatically using Azure CLI. See also Create
and manage Azure Database for PostgreSQL firewall rules using Azure CLI

Troubleshooting the database server firewall


Consider the following points when access to the Microsoft Azure Database for PostgreSQL Server service does
not behave as you expect:
Changes to the allow list have not taken effect yet: There may be as much as a five-minute delay for
changes to the Azure Database for PostgreSQL Server firewall configuration to take effect.
The login is not authorized or an incorrect password was used: If a login does not have permissions
on the Azure Database for PostgreSQL server or the password used is incorrect, the connection to the
Azure Database for PostgreSQL server is denied. Creating a firewall setting only provides clients with an
opportunity to attempt connecting to your server; each client must still provide the necessary security
credentials.
For example, using a JDBC client, the following error may appear.

java.util.concurrent.ExecutionException: java.lang.RuntimeException: org.postgresql.util.PSQLException: FATAL:


password authentication failed for user "yourusername"

Dynamic IP address: If you have an Internet connection with dynamic IP addressing and you are having
trouble getting through the firewall, you could try one of the following solutions:
Ask your Internet Service Provider (ISP ) for the IP address range assigned to your client computers that
access the Azure Database for PostgreSQL Server, and then add the IP address range as a firewall rule.
Get static IP addressing instead for your client computers, and then add the static IP address as a firewall
rule.

Next steps
For articles on creating server-level and database-level firewall rules, see:
Create and manage Azure Database for PostgreSQL firewall rules using the Azure portal
Create and manage Azure Database for PostgreSQL firewall rules using Azure CLI
Configure SSL connectivity in Azure Database for
PostgreSQL
4/25/2018 • 4 minutes to read • Edit Online

Azure Database for PostgreSQL prefers connecting your client applications to the PostgreSQL service using
Secure Sockets Layer (SSL ). Enforcing SSL connections between your database server and your client
applications helps protect against "man in the middle" attacks by encrypting the data stream between the server
and your application.
By default, the PostgreSQL database service is configured to require SSL connection. Optionally, you can disable
requiring SSL to connect to your database service if your client application does not support SSL connectivity.

Enforcing SSL connections


For all Azure Database for PostgreSQL servers provisioned through the Azure portal and CLI, enforcement of
SSL connections is enabled by default.
Likewise, connection strings that are pre-defined in the "Connection Strings" settings under your server in the
Azure portal include the required parameters for common languages to connect to your database server using
SSL. The SSL parameter varies based on the connector, for example "ssl=true" or "sslmode=require" or
"sslmode=required" and other variations.

Configure Enforcement of SSL


You can optionally disable enforcing SSL connectivity. Microsoft Azure recommends to always enable Enforce
SSL connection setting for enhanced security.
Using the Azure portal
Visit your Azure Database for PostgreSQL server and click Connection security. Use the toggle button to enable
or disable the Enforce SSL connection setting. Then, click Save.

You can confirm the setting by viewing the Overview page to see the SSL enforce status indicator.
Using Azure CLI
You can enable or disable the ssl-enforcement parameter using Enabled or Disabled values respectively in
Azure CLI.
az postgres server update --resource-group myresourcegroup --name mydemoserver --ssl-enforcement Enabled

Ensure your application or framework supports SSL connections


Many common application frameworks that use PostgreSQL for their database services, such as Drupal and
Django, do not enable SSL by default during installation. Enabling SSL connectivity must be done after
installation or through CLI commands specific to the application. If your PostgreSQL server is enforcing SSL
connections and the associated application is not configured properly, the application may fail to connect to your
database server. Consult your application's documentation to learn how to enable SSL connections.

Applications that require certificate verification for SSL connectivity


In some cases, applications require a local certificate file generated from a trusted Certificate Authority (CA)
certificate file (.cer) to connect securely. See the following steps to obtain the .cer file, decode the certificate and
bind it to your application.
Download the certificate file from the Certificate Authority (CA )
The certificate needed to communicate over SSL with your Azure Database for PostgreSQL server is located here.
Download the certificate file locally.
Download and install OpenSSL on your machine
To decode the certificate file needed for your application to connect securely to your database server, you need to
install OpenSSL on your local computer.
For Linux, OS X, or Unix
The OpenSSL libraries are provided in source code directly from the OpenSSL Software Foundation. The
following instructions guide you through the steps necessary to install OpenSSL on your Linux PC. This article
uses commands known to work on Ubuntu 12.04 and higher.
Open a terminal session and download OpenSSL.

wget http://www.openssl.org/source/openssl-1.1.0e.tar.gz

Extract the files from the downloaded package.

tar -xvzf openssl-1.1.0e.tar.gz

Enter the directory where the files were extracted. By default, it should be as follows.

cd openssl-1.1.0e

Configure OpenSSL by executing the following command. If you want the files in a folder different than
/usr/local/openssl, make sure to change the following as appropriate.

./config --prefix=/usr/local/openssl --openssldir=/usr/local/openssl

Now that OpenSSL is configured properly, you need to compile it to convert your certificate. To compile, run the
following command:

make
Once compilation is complete, you're ready to install OpenSSL as an executable by running the following
command:

make install

To confirm that you've successfully installed OpenSSL on your system, run the following command and check to
make sure you get the same output.

/usr/local/openssl/bin/openssl version

If successful you should see the following message.

OpenSSL 1.1.0e 7 Apr 2014

For Windows
Installing OpenSSL on a Windows PC can be done in the following ways:
1. (Recommended) Using the built-in Bash for Windows functionality in Window 10 and above, OpenSSL is
installed by default. Instructions on how to enable Bash for Windows functionality in Windows 10 can be found
here.
2. Through downloading a Win32/64 application provided by the community. While the OpenSSL Software
Foundation does not provide or endorse any specific Windows installers, they provide a list of available
installers here.
Decode your certificate file
The downloaded Root CA file is in encrypted format. Use OpenSSL to decode the certificate file. To do so, run this
OpenSSL command:

openssl x509 -inform DER -in BaltimoreCyberTrustRoot.crt -text -out root.crt

Connecting to Azure Database for PostgreSQL with SSL certificate authentication


Now that you have successfully decoded your certificate, you can now connect to your database server securely
over SSL. To allow server certificate verification, the certificate must be placed in the file ~/.postgresql/root.crt in
the user's home directory. (On Microsoft Windows the file is named %APPDATA%\postgresql\root.crt.). The
following provides instructions for connecting to Azure Database for PostgreSQL.
Using psql command-line utility
The following example shows how to successfully connect to your PostgreSQL server using the psql command-
line utility. Use the root.crt file created and the sslmode=verify-ca or sslmode=verify-full option.
Using the PostgreSQL command-line interface, execute the following command:

psql "sslmode=verify-ca sslrootcert=root.crt host=mydemoserver.postgres.database.azure.com dbname=postgres


user=mylogin@mydemoserver"

If successful, you receive the following output:


Password for user mylogin@mydemoserver:
psql (9.6.2)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=>

Using pgAdmin GUI tool


Configuring pgAdmin 4 to connect securely over SSL requires you to set the SSL mode = Verify-CA or
SSL mode = Verify-Full as follows:

Next steps
Review various application connectivity options following Connection libraries for Azure Database for
PostgreSQL.
Use Virtual Network service endpoints and rules for
Azure Database for PostgreSQL
5/29/2018 • 6 minutes to read • Edit Online

Virtual network rules are one firewall security feature that controls whether your Azure Database for PostgreSQL
server accepts communications that are sent from particular subnets in virtual networks. This article explains why
the virtual network rule feature is sometimes your best option for securely allowing communication to your Azure
Database for PostgreSQL server.
To create a virtual network rule, there must first be a virtual network (VNet) and a virtual network service endpoint
for the rule to reference. The following picture illustrates how a Virtual Network service endpoint works with
Azure Database for PostgreSQL:

NOTE
For Azure Database for PostgreSQL, this feature is available in public preview in all regions of Azure public cloud where Azure
Database for PostgreSQL is deployed.

Terminology and description


Virtual network: You can have virtual networks associated with your Azure subscription.
Subnet: A virtual network contains subnets. Any Azure virtual machines (VMs) that you have are assigned to
subnets. One subnet can contain multiple VMs or other compute nodes. Compute nodes that are outside of your
virtual network cannot access your virtual network unless you configure your security to allow access.
Virtual Network service endpoint: A Virtual Network service endpoint is a subnet whose property values
include one or more formal Azure service type names. In this article we are interested in the type name of
Microsoft.Sql, which refers to the Azure service named SQL Database. This service tag also applies to the Azure
Database for PostgreSQL and MySQL services. It is important to note when applying the Microsoft.Sql service
tag to a VNet service endpoint it will configure service endpoint traffic for all Azure SQL Database, Azure
Database for PostgreSQL and Azure Database for MySQL servers on the subnet.
Virtual network rule: A virtual network rule for your Azure Database for PostgreSQL server is a subnet that is
listed in the access control list (ACL ) of your Azure Database for PostgreSQL server. To be in the ACL for your
Azure Database for PostgreSQL server, the subnet must contain the Microsoft.Sql type name.
A virtual network rule tells your Azure Database for PostgreSQL server to accept communications from every
node that is on the subnet.

Benefits of a virtual network rule


Until you take action, the VMs on your subnets cannot communicate with your Azure Database for PostgreSQL
server. One action that establishes the communication is the creation of a virtual network rule. The rationale for
choosing the VNet rule approach requires a compare-and-contrast discussion involving the competing security
options offered by the firewall.
A. Allow access to Azure services
The Connection security pane has an ON/OFF button that is labeled Allow access to Azure services. The ON
setting allows communications from all Azure IP addresses and all Azure subnets. These Azure IPs or subnets
might not be owned by you. This ON setting is probably more open than you want your Azure Database for
PostgreSQL Database to be. The virtual network rule feature offers much finer granular control.
B. IP rules
The Azure Database for PostgreSQL firewall allows you to specify IP address ranges from which communications
are accepted into the Azure Database for PostgreSQL Database. This approach is fine for stable IP addresses that
are outside the Azure private network. But many nodes inside the Azure private network are configured with
dynamic IP addresses. Dynamic IP addresses might change, such as when your VM is restarted. It would be folly
to specify a dynamic IP address in a firewall rule, in a production environment.
You can salvage the IP option by obtaining a static IP address for your VM. For details, see Configure private IP
addresses for a virtual machine by using the Azure portal.
However, the static IP approach can become difficult to manage, and it is costly when done at scale. Virtual
network rules are easier to establish and to manage.
C. Cannot yet have Azure Database for PostgreSQL on a subnet without defining a service endpoint
If your Microsoft.Sql server was a node on a subnet in your virtual network, all nodes within the virtual network
could communicate with your Azure Database for PostgreSQL server. In this case, your VMs could communicate
with Azure Database for PostgreSQL without needing any virtual network rules or IP rules.
However as of May 2018, the Azure Database for PostgreSQL service is not yet among the services that can be
assigned directly to a subnet.

Details about virtual network rules


This section describes several details about virtual network rules.
Only one geographic region
Each Virtual Network service endpoint applies to only one Azure region. The endpoint does not enable other
regions to accept communication from the subnet.
Any virtual network rule is limited to the region that its underlying endpoint applies to.
Server-level, not database -level
Each virtual network rule applies to your whole Azure Database for PostgreSQL server, not just to one particular
database on the server. In other words, virtual network rule applies at the server-level, not at the database-level.
Security administration roles
There is a separation of security roles in the administration of Virtual Network service endpoints. Action is
required from each of the following roles:
Network Admin: Turn on the endpoint.
Database Admin: Update the access control list (ACL ) to add the given subnet to the Azure Database for
PostgreSQL server.
RBAC alternative:
The roles of Network Admin and Database Admin have more capabilities than are needed to manage virtual
network rules. Only a subset of their capabilities is needed.
You have the option of using role-based access control (RBAC ) in Azure to create a single custom role that has
only the necessary subset of capabilities. The custom role could be used instead of involving either the Network
Admin or the Database Admin. The surface area of your security exposure is lower if you add a user to a custom
role, versus adding the user to the other two major administrator roles.

NOTE
In some cases the Azure Database for PostgreSQL and the VNet-subnet are in different subscriptions. In these cases you
must ensure the following configurations:
Both subscriptions must be in the same Azure Active Directory tenant.
The user has the required permissions to initiate operations, such as enabling service endpoints and adding a VNet-
subnet to the given Server.

Limitations
For Azure Database for PostgreSQL, the virtual network rules feature has the following limitations:
In the firewall for your Azure Database for PostgreSQL, each virtual network rule references a subnet. All
these referenced subnets must be hosted in the same geographic region that hosts the Azure Database for
PostgreSQL.
Each Azure Database for PostgreSQL server can have up to 128 ACL entries for any given virtual network.
Virtual network rules apply only to Azure Resource Manager virtual networks; and not to classic
deployment model networks.
Turning ON virtual network service endpoints to Azure Database for PostgreSQL using the Microsoft.Sql
service tag also enables the endpoints for all Azure Database services: Azure Database for MySQL, Azure
Database for PostgreSQL, Azure SQL Database and Azure SQL Data Warehouse.
At the time of public preview, there is no support for VNet move operations. To move a virtual network rule,
drop and recreate it.
Support for VNet service endpoints is only for General Purpose and Memory Optimized servers.
On the firewall, IP address ranges do apply to the following networking items, but virtual network rules do
not:
Site-to-Site (S2S ) virtual private network (VPN )
On-premises via ExpressRoute

ExpressRoute
If your network is connected to the Azure network through use of ExpressRoute, each circuit is configured with two
public IP addresses at the Microsoft Edge. The two IP addresses are used to connect to Microsoft Services, such as
to Azure Storage, by using Azure Public Peering.
To allow communication from your circuit to Azure Database for PostgreSQL, you must create IP network rules for
the public IP addresses of your circuits. In order to find the public IP addresses of your ExpressRoute circuit, open a
support ticket with ExpressRoute by using the Azure portal.

Related articles
Azure virtual networks
Azure virtual network service endpoints

Next steps
For articles on creating VNet rules, see:
Create and manage Azure Database for PostgreSQL VNet rules using the Azure portal
Create and manage Azure Database for PostgreSQL VNet rules using Azure CLI
Overview of business continuity with Azure Database
for PostgreSQL
6/15/2018 • 3 minutes to read • Edit Online

This overview describes the capabilities that Azure Database for PostgreSQL provides for business continuity and
disaster recovery. Learn about options for recovering from disruptive events that could cause data loss or cause
your database and application to become unavailable. Learn what to do when a user or application error affects
data integrity, an Azure region has an outage, or your application requires maintenance.

Features that you can use to provide business continuity


Azure Database for PostgreSQL provides business continuity features that include automated backups and the
ability for users to initiate geo-restore. Each has different characteristics for Estimated Recovery Time (ERT) and
potential data loss. Once you understand these options, you can choose among them, and use them together for
different scenarios. As you develop your business continuity plan, you need to understand the maximum
acceptable time before the application fully recovers after the disruptive event - this is your Recovery Time
Objective (RTO ). You also need to understand the maximum amount of recent data updates (time interval) the
application can tolerate losing when recovering after the disruptive event - this is your Recovery Point Objective
(RPO ).
The following table compares the ERT and RPO for the available features:

CAPABILITY BASIC GENERAL PURPOSE MEMORY OPTIMIZED

Point in Time Restore from Any restore point within the Any restore point within the Any restore point within the
backup retention period retention period retention period

Geo-restore from geo- Not supported ERT < 12 h ERT < 12 h


replicated backups RPO < 1 h RPO < 1 h

IMPORTANT
If you delete the server, all databases that belong to the server are also deleted and cannot be recovered. You cannot restore
a deleted server.

Recover a server after a user or application error


You can use the service’s backups to recover a server from various disruptive events. A user may accidentally
delete some data, inadvertently drop an important table, or even drop an entire database. An application might
accidentally overwrite good data with bad data due to an application defect, and so on.
You can perform a point-in-time-restore to create a copy of your server to a known good point in time. This point
in time must be within the backup retention period you have configured for your server. After the data is restored
to the new server, you can either replace the original server with the newly restored server or copy the needed
data from the restored server into the original server.

Recover from an Azure regional data center outage


Although rare, an Azure data center can have an outage. When an outage occurs, it causes a business disruption
that might only last a few minutes, but could last for hours.
One option is to wait for your server to come back online when the data center outage is over. This works for
applications that can afford to have the server offline for some period of time, for example a development
environment. When data center has an outage, you do not know how long the outage might last, so this option
only works if you don't need your server for a while.
The other option is to use the Azure Database for PostgreSQL's geo-restore feature that restores the server using
geo-redundant backups. These backups are accessible even when the region your server is hosted in is offline. You
can restore from these backups to any other region and bring your server back online.

IMPORTANT
Geo-restore is only possible if you provisioned the server with geo-redundant backup storage.

Next steps
To learn more about the automated backups, see Backups in Azure Database for PostgreSQL.
To restore to a point in time using the Azure portal, seerestore database to a point in time using the Azure
portal.
To restore to a point in time using Azure CLI, seerestore database to a point in time using CLI.
Backup and restore in Azure Database for
PostgreSQL
6/15/2018 • 4 minutes to read • Edit Online

Azure Database for PostgreSQL automatically creates server backups and stores them in user configured locally
redundant or geo-redundant storage. Backups can be used to restore your server to a point-in-time. Backup and
restore are an essential part of any business continuity strategy because they protect your data from accidental
corruption or deletion.

Backups
Azure Database for PostgreSQL takesfull,differential, andtransaction log backups. These backups allow you to
restore a server to any point-in-time within your configured backup retention period. The default backup retention
period is seven days. You can optionally configure it up to 35 days. All backups are encrypted using AES 256-bit
encryption.
Backup frequency
Generally, full backups occur weekly, differential backups occur twice a day, and transaction log backups occur
every five minutes. The first full backup is scheduled immediately after a server is created. The initial backup can
take longer on a large restored server. The earliest point in time that a new server can be restored to is the time at
which the initial full backup is complete.
Backup redundancy options
Azure Database for PostgreSQL provides the flexibility to choose between locally redundant or geo-redundant
backup storage in the General Purpose and Memory Optimized tiers. When the backups are stored in geo-
redundant backup storage, they are not only stored within the region in which your server is hosted, but are also
replicated to a paired data center. This provides better protection and ability to restore your server in a different
region in the event of a disaster. The Basic tier only offers locally redundant backup storage.

IMPORTANT
Configuring locally redundant or geo-redundant storage for backup is only allowed during server create. Once the server is
provisioned, you cannot change the backup storage redundancy option.

Backup storage cost


Azure Database for PostgreSQL provides up to 100% of your provisioned server storage as backup storage at no
additional cost. Typically, this is suitable for a backup retention of seven days. Any additional backup storage used
is charged in GB -month.
For example, if you have provisioned a server with 250 GB, you have 250 GB of backup storage at no additional
charge. Storage in excess of 250 GB is charged.

Restore
In Azure Database for PostgreSQL, performing a restore creates a new server from the original server's backups.
There are two types of restore available:
Point-in-time restore is available with either backup redundancy option and creates a new server in the same
region as your original server.
Geo-restore is available only if you configured your server for geo-redundant storage and it allows you to
restore your server to a different region.
The estimated time of recovery depends on several factors including the database sizes, the transaction log size,
the network bandwidth, and the total number of databases recovering in the same region at the same time. The
recovery time is usually less than 12 hours.

IMPORTANT
If you delete the server, all databases that belong to the server are also deleted and cannot be recovered. You cannot restore
a deleted server.

Point-in-time restore
Independent of your backup redundancy option, you can perform a restore to any point in time within your
backup retention period. A new server is created in the same Azure region as the original server. It is created with
the original server's configuration for the pricing tier, compute generation, number of vCores, storage size, backup
retention period, and backup redundancy option.
Point-in-time restore is useful in multiple scenarios. For example, when a user accidentally deletes data, drops an
important table or database, or if an application accidentally overwrites good data with bad data due to an
application defect.
You may need to wait for the next transaction log backup to be taken before you can restore to a point in time
within the last five minutes.
Geo -restore
You can restore a server to another Azure region where the service is available if you have configured your server
for geo-redundant backups. Geo-restore is the default recovery option when your server is unavailable because of
an incident in the region where the server is hosted. If a large-scale incident in a region results in unavailability of
your database application, you can restore a server from the geo-redundant backups to a server in any other
region. There is a delay between when a backup is taken and when it is replicated to different region. This delay
can be up to an hour, so, if a disaster occurs, there can be up to one hour data loss.
Perform post-restore tasks
After a restore from either recovery mechanism, you should perform the following tasks to get your users and
applications back up and running:
If the new server is meant to replace the original server, redirect clients and client applications to the new
server
Ensure appropriate server-level firewall rules are in place for users to connect
Ensure appropriate logins and database level permissions are in place
Configure alerts, as appropriate

Next steps
To learn more about business continuity, see thebusiness continuity overview.
To restore to a point in time using the Azure portal, seerestore database to a point in time using the Azure
portal.
To restore to a point in time using Azure CLI, seerestore database to a point in time using CLI.
Monitoring in Azure Database for PostgreSQL
2/27/2018 • 2 minutes to read • Edit Online

Monitoring data about your servers helps you troubleshoot and optimize for your workload. Azure Database for
PostgreSQL provides various metrics that give insight into the behavior of the resources supporting the
PostgreSQL server.

Metrics
All Azure metrics have a one-minute frequency, and each metric provides 30 days of history. You can configure
alerts on the metrics. For step by step guidance, see How to set up alerts. Other tasks include setting up automated
actions, performing advanced analytics, and archiving history. For more information, see the Azure Metrics
Overview.
List of metrics
These metrics are available for Azure Database for PostgreSQL:

METRIC METRIC DISPLAY NAME UNIT DESCRIPTION

cpu_percent CPU percent Percent The percentage of CPU in


use.

memory_percent Memory percent Percent The percentage of memory


in use.

io_consumption_percent IO percent Percent The percentage of IO in use.

storage_percent Storage percentage Percent The percentage of storage


used out of the server's
maximum.

storage_used Storage used Bytes The amount of storage in


use. The storage used by the
service includes the
database files, transaction
logs, and the server logs.

storage_limit Storage limit Bytes The maximum storage for


this server.

active_connections Total active connections Count The number of active


connections to the server.

connections_failed Total failed connections Count The number of failed


connections to the server.

Next steps
See How to set up alerts for guidance on creating an alert on a metric.
For more information on how to access and export metrics using the Azure portal, REST API, or CLI, see the
Azure Metrics Overview.
Connection libraries for Azure Database for
PostgreSQL
2/27/2018 • 2 minutes to read • Edit Online

This article lists libraries and drivers that developers can use to develop applications to connect to and query
Azure Database for PostgreSQL.

Client interfaces
Most language client libraries used to connect to PostgreSQL server are external projects and are distributed
independently. The libraries listed are supported on the Windows, Linux, and Mac platforms, for connecting to
Azure Database for PostgreSQL. Several quickstart examples are listed in the Next steps section.

LANGUAGE CLIENT INTERFACE ADDITIONAL INFORMATION DOWNLOAD

Python psycopg DB API 2.0-compliant Download

PHP php-pgsql Database extension Install

Node.js Pg npm package Pure JavaScript non- Install


blocking client

Java JDBC Type 4 JDBC driver Download

Ruby Pg gem Ruby Interface Download

Go Package pq Pure Go postgres driver Install

C#/ .NET Npgsql ADO.NET Data Provider Download

ODBC psqlODBC ODBC Driver Download

C libpq Primary C language Included


interface

C++ libpqxx New-style C++ interface Download

Next steps
Read these quickstarts on how to connect to and query Azure Database for PostgreSQL by using your language
of choice:
Python | Node.JS | Java | Ruby | PHP | .NET (C#) | Go
Create users in Azure Database for PostgreSQL
server
7/19/2018 • 3 minutes to read • Edit Online

This article describes how you can create users in an Azure Database for PostgreSQL server.

The server admin account


When you first created your Azure Database for PostgreSQL, you provided a server admin user name and
password. For more information, you can follow the Quickstart to see the step-by-step approach. Since the server
admin user name is a custom name, you can locate the chosen server admin user name from the Azure portal.
The Azure Database for PostgreSQL server is created with the 3 default roles defined. You can see these roles by
running the command: SELECT rolname FROM pg_roles;
azure_pg_admin
azure_superuser
your server admin user
Your server admin user is a member of the azure_pg_admin role. However, the server admin account is not part of
the azure_superuser role. Since this service is a managed PaaS service, only Microsoft is part of the super user role.
The PostgreSQL engine uses privileges to control access to database objects, as discussed in the PostgreSQL
product documentation. In Azure Database for PostgreSQL, the server admin user is granted these privileges:
LOGIN, NOSUPERUSER, INHERIT, CREATEDB, CREATEROLE, NOREPLICATION
The server admin user account can be used to create additional users and grant those users into the
azure_pg_admin role. Also, the server admin account can be used to create less privileged users and roles that have
access to individual databases and schemas.

How to create additional admin users in Azure Database for


PostgreSQL
1. Get the connection information and admin user name. To connect to your database server, you need the full
server name and admin sign-in credentials. You can easily find the server name and sign-in information
from the server Overview page or the Properties page in the Azure portal.
2. Use the admin account and password to connect to your database server. Use your preferred client tool,
such as pgAdmin or psql. If you are unsure of how to connect, see Connect to the PostgreSQL Database by
using psql in Cloud Shell
3. Edit and run the following SQL code. Replace your new user name for the placeholder value <new_user>,
and replace the placeholder password with your own strong password.

CREATE ROLE <new_user> WITH LOGIN NOSUPERUSER INHERIT CREATEDB CREATEROLE NOREPLICATION PASSWORD
'<StrongPassword!>';

GRANT azure_pg_admin TO <new_user>;

How to create database users in Azure Database for PostgreSQL


1. Get the connection information and admin user name. To connect to your database server, you need the full
server name and admin sign-in credentials. You can easily find the server name and sign-in information
from the server Overview page or the Properties page in the Azure portal.
2. Use the admin account and password to connect to your database server. Use your preferred client tool,
such as pgAdmin or psql.
3. Edit and run the following SQL code. Replace the placeholder value <db_user> with your intended new user
name, and placeholder value <newdb> with your own database name. Replace the placeholder password
with your own strong password.
This sql code syntax creates a new database named testdb, for example purposes. Then it creates a new user
in the PostgreSQL service, and grants connect privileges to the new database for that user.

CREATE DATABASE <newdb>;

CREATE ROLE <db_user> WITH LOGIN NOSUPERUSER INHERIT CREATEDB NOCREATEROLE NOREPLICATION PASSWORD
'<StrongPassword!>';

GRANT CONNECT ON DATABASE <newdb> TO <db_user>;

4. Using an admin account, you may need to grant additional privileges to secure the objects in the database.
Refer to the PostgreSQL documentation for further details on database roles and privileges. For example:

GRANT ALL PRIVILEGES ON DATABASE <newdb> TO <db_user>;

5. Log in to your server, specifying the designated database, using the new user name and password. This
example shows the psql command line. With this command, you are prompted for the password for the user
name. Replace your own server name, database name, and user name.

psql --host=mydemoserver.postgres.database.azure.com --port=5432 --username=db_user@mydemoserver --


dbname=newdb

Next steps
Open the firewall for the IP addresses of the new users' machines to enable them to connect: Create and manage
Azure Database for PostgreSQL firewall rules by using the Azure portal or Azure CLI.
For more information regarding user account management, see PostgreSQL product documentation for Database
Roles and Privileges, GRANT Syntax, and Privileges.
Create and manage Azure Database for PostgreSQL
firewall rules using the Azure portal
2/27/2018 • 3 minutes to read • Edit Online

Server-level firewall rules enable administrators to access an Azure Database for PostgreSQL Server from a
specified IP address or range of IP addresses.

Prerequisites
To step through this how -to guide, you need:
A server Create an Azure Database for PostgreSQL

Create a server-level firewall rule in the Azure portal


1. On the PostgreSQL server page, under Settings heading, click Connection security to open the
Connection security page for the Azure Database for PostgreSQL.

2. Click Add My IP on the toolbar. This automatically creates a firewall rule with the public IP address of your
computer, as perceived by the Azure system.
3. Verify your IP address before saving the configuration. In some situations, the IP address observed by
Azure portal differs from the IP address used when accessing the internet and Azure servers. Therefore,
you may need to change the Start IP and End IP to make the rule function as expected. Use a search engine
or other online tool to check your own IP address. For example, search for "what is my IP."

4. Add additional address ranges. In the firewall rules for the Azure Database for PostgreSQL, you can specify
a single IP address, or a range of addresses. If you want to limit the rule to a single IP address, type the
same address in the field for Start IP and End IP. Opening the firewall enables administrators, users, and
applications to log in to any database on the PostgreSQL server to which they have valid credentials.
5. Click Save on the toolbar to save this server-level firewall rule. Wait for the confirmation that the update to
the firewall rules was successful.

Connecting from Azure


To allow applications from Azure to connect to your Azure Database for PostgreSQL server, Azure connections
must be enabled. For example, to host an Azure Web Apps application, or an application that runs in an Azure VM,
or to connect from an Azure Data Factory data management gateway. The resources do not need to be in the
same Virtual Network (VNet) or Resource Group for the firewall rule to enable those connections. When an
application from Azure attempts to connect to your database server, the firewall verifies that Azure connections
are allowed. There are a couple of methods to enable these types of connections. A firewall setting with starting
and ending address equal to 0.0.0.0 indicates these connections are allowed. Alternatively, you can set the Allow
access to Azure services option to ON in the portal from the Connection security pane and hit Save. If the
connection attempt is not allowed, the request does not reach the Azure Database for PostgreSQL server.
IMPORTANT
This option configures the firewall to allow all connections from Azure including connections from the subscriptions of other
customers. When selecting this option, make sure your login and user permissions limit access to only authorized users.

Manage existing server-level firewall rules through the Azure portal


Repeat the steps to manage the firewall rules.
To add the current computer, click the button to + Add My IP. Click Save to save the changes.
To add additional IP addresses, type in the Rule Name, Start IP Address, and End IP Address. Click Save to
save the changes.
To modify an existing rule, click any of the fields in the rule and modify. Click Save to save the changes.
To delete an existing rule, click the ellipsis […] and click Delete to remove the rule. Click Save to save the
changes.

Next steps
Similarly, you can script to Create and manage Azure Database for PostgreSQL firewall rules using Azure CLI.
For help in connecting to an Azure Database for PostgreSQL server, see Connection libraries for Azure
Database for PostgreSQL.
Create and manage Azure Database for PostgreSQL
firewall rules using Azure CLI
5/7/2018 • 3 minutes to read • Edit Online

Server-level firewall rules enable administrators to manage access to an Azure Database for PostgreSQL Server
from a specific IP address or range of IP addresses. Using convenient Azure CLI commands, you can create,
update, delete, list, and show firewall rules to manage your server. For an overview of Azure Database for
PostgreSQL firewall rules, see Azure Database for PostgreSQL Server firewall rules

Prerequisites
To step through this how -to guide, you need:
Install Azure CLI 2.0 command-line utility or use the Azure Cloud Shell in the browser.
An Azure Database for PostgreSQL server and database.

Configure firewall rules for Azure Database for PostgreSQL


The az postgres server firewall-rule commands are used to configure firewall rules.

List firewall rules


To list the existing server firewall rules, run the az postgres server firewall-rule list command.

az postgres server firewall-rule list --resource-group myresourcegroup --server-name mydemoserver

The output lists the firewall rules, if any, by default in JSON format. You may use the switch --output table for a
more readable table format as the output.

az postgres server firewall-rule list --resource-group myresourcegroup --server-name mydemoserver --output


table

Create firewall rule


To create a new firewall rule on the server, run the az postgres server firewall-rule create command.
By specifying 0.0.0.0 as the --start-ip-address and 255.255.255.255 as the --end-ip-address range, the
following example allows all IP addresses to access the server mydemoserver.postgres.database.azure.com

az postgres server firewall-rule create --resource-group myresourcegroup --server-name mydemoserver --name


AllowIpRange --start-ip-address 0.0.0.0 --end-ip-address 255.255.255.255

To allow access to a singular IP address, provide the same address in the --start-ip-address and
--end-ip-address , as in this example.

az postgres server firewall-rule create --resource-group myresourcegroup --server-name mydemoserver --name


AllowSingleIpAddress --start-ip-address 13.83.152.1 --end-ip-address 13.83.152.1
To allow applications from Azure IP addresses to connect to your Azure Database for PostgreSQL server, provide
the IP address 0.0.0.0 as the Start IP and End IP, as in this example.

az postgres server firewall-rule create --resource-group myresourcegroup --server-name mydemoserver --name


AllowAllAzureIps --start-ip-address 0.0.0.0 --end-ip-address 0.0.0.0

IMPORTANT
This option configures the firewall to allow all connections from Azure including connections from the subscriptions of other
customers. When selecting this option, make sure your login and user permissions limit access to only authorized users.

Upon success, the command output lists the details of the firewall rule you have created, by default in JSON
format. If there is a failure, the output shows an error message instead.

Update firewall rule


Update an existing firewall rule on the server using az postgres server firewall-rule update command. Provide the
name of the existing firewall rule as input, and the start IP and end IP attributes to update.

az postgres server firewall-rule update --resource-group myresourcegroup --server-name mydemoserver --name


AllowIpRange --start-ip-address 13.83.152.0 --end-ip-address 13.83.152.255

Upon success, the command output lists the details of the firewall rule you have updated, by default in JSON
format. If there is a failure, the output shows an error message instead.

NOTE
If the firewall rule does not exist, it gets created by the update command.

Show firewall rule details


You can also show the details of an existing server-level firewall rule by running az postgres server firewall-rule
show command.

az postgres server firewall-rule show --resource-group myresourcegroup --server-name mydemoserver --name


AllowIpRange

Upon success, the command output lists the details of the firewall rule you have specified, by default in JSON
format. If there is a failure, the output shows an error message instead.

Delete firewall rule


To revoke access for an IP range to the server, delete an existing firewall rule by executing the az postgres server
firewall-rule delete command. Provide the name of the existing firewall rule.

az postgres server firewall-rule delete --resource-group myresourcegroup --server-name mydemoserver --name


AllowIpRange

Upon success, there is no output. Upon failure, the error message text is returned.
Next steps
Similarly, you can use a web browser to Create and manage Azure Database for PostgreSQL firewall rules
using the Azure portal.
Understand more about Azure Database for PostgreSQL Server firewall rules.
For help in connecting to an Azure Database for PostgreSQL server, see Connection libraries for Azure
Database for PostgreSQL.
How to backup and restore a server in Azure
Database for PostgreSQL using the Azure portal
4/13/2018 • 3 minutes to read • Edit Online

Backup happens automatically


Azure Database for PostgreSQL servers are backed up periodically to enable Restore features. Using this feature
you may restore the server and all its databases to an earlier point-in-time, on a new server.

Set backup configuration


You make the choice between configuring your server for either locally redundant backups or geographically
redundant backups at server creation, in the Pricing Tier window.

NOTE
After a server is created, the kind of redundancy it has, geographically redundant vs locally redundant, can't be switched.

While creating a server through the Azure portal, the Pricing Tier window is where you select either Locally
Redundant or Geographically Redundant backups for your server. This window is also where you select the
Backup Retention Period - how long (in number of days) you want the server backups stored for.

For more information about setting these values during create, see the Azure Database for PostgreSQL server
quickstart.
The backup retention period of a server can be changed through the following steps:
1. Sign into the Azure portal.
2. Select your Azure Database for PostgreSQL server. This action opens the Overview page.
3. Select Pricing Tier from the menu, under SETTINGS. Using the slider you can change the Backup
Retention Period to your preference between 7 and 35 days. In the screenshot below it has been
increased to 34 days.

4. Click OK to confirm the change.


The backup retention period governs how far back in time a point-in-time restore can be retrieved, since it's based
on backups available. Point-in-time restore is described further in the following section.

Point-in-time restore
Azure Database for PostgreSQL allows you to restore the server back to a point-in-time and into to a new copy of
the server. You can use this new server to recover your data, or have your client applications point to this new
server.
For example, if a table was accidentally dropped at noon today, you could restore to the time just before noon and
retrieve the missing table and data from that new copy of the server. Point-in-time restore is at the server level,
not at the database level.
The following steps restore the sample server to a point-in-time:
1. In the Azure portal, select your Azure Database for PostgreSQL server.
2. In the toolbar of the server's Overview page, select Restore.
3. Fill out the Restore form with the required information:

Restore point: Select the point-in-time you want to restore to.


Target server: Provide a name for the new server.
Location: You cannot select the region. By default it is same as the source server.
Pricing tier: You cannot change these parameters when doing a point-in-time restore. It is same as the
source server.
4. Click OK to restore the server to restore to a point-in-time.
5. Once the restore finishes, locate the new server that is created to verify the data was restored as expected.

NOTE
The new server created by point-in-time restore has the same server admin login name and password that was valid for the
existing server at the point-in-time chose. You can change the password from the new server's Overview page.

Geo restore
If you configured your server for geographically redundant backups, a new server can be created from the backup
of that existing server. This new server can be created in any region that Azure Database for PostgreSQL is
available.
1. Select the Create a resource button (+) in the upper-left corner of the portal. Select Databases > Azure
Database for PostgreSQL.
2. In the form's Select Source dropdown, choose Backup. This action loads a list of servers that have geo
redundant backups enabled. Select one of these backups to be the source of your new server.
NOTE
When a server is first created it may not be immediately available for geo restore. It may take a few hours for the
necessary metadata to be populated.

3. Fill out the rest of the form with your preferences. You can select any Location. After selecting the location,
you can select Pricing Tier. By default the parameters for the existing server you are restoring from are
displayed. You can click OK without making any changes to inherit those settings. Or you can change
Compute Generation (if available in the region you have chosen), number of vCores, Backup Retention
Period, and Backup Redundancy Option. Changing Pricing Tier (Basic, General Purpose, or Memory
Optimized) or Storage size during restore is not supported.

NOTE
The new server created by geo restore has the same server admin login name and password that was valid for the existing
server at the time the restore was initiated. The password can be changed from the new server's Overview page.

Next steps
Learn more about the service's backups.
Learn more about business continuity options.
How to back up and restore a server in Azure
Database for PostgreSQL using the Azure CLI
7/20/2018 • 5 minutes to read • Edit Online

Backup happens automatically


Azure Database for PostgreSQL servers are backed up periodically to enable Restore features. Using this feature
you may restore the server and all its databases to an earlier point-in-time, on a new server.

Prerequisites
To complete this how -to guide, you need:
An Azure Database for PostgreSQL server and database

Open Azure Cloud Shell


Azure Cloud Shell is a free, interactive shell that you can use to run the steps in this article. Common Azure tools
are preinstalled and configured in Cloud Shell for you to use with your account. Just select the Copy button to
copy the code, paste it in Cloud Shell, and then press Enter to run it. There are a few ways to open Cloud Shell:

Select Try It in the upper-right corner of a code block.

Open Cloud Shell in your browser.

Select the Cloud Shell button on the menu in the upper-right


corner of the Azure portal.

IMPORTANT
This how-to guide requires that you use Azure CLI version 2.0 or later. To confirm the version, at the Azure CLI command
prompt, enter az --version . To install or upgrade, see Install Azure CLI 2.0.

Set backup configuration


You make the choice between configuring your server for either locally redundant backups or geographically
redundant backups at server creation.

NOTE
After a server is created, the kind of redundancy it has, geographically redundant vs locally redundant, can't be switched.

While creating a server via the az postgres server create command, the --geo-redundant-backup parameter
decides your Backup Redundancy Option. If Enabled , geo redundant backups are taken. Or if Disabled locally
redundant backups are taken.
The backup retention period is set by the parameter --backup-retention-days .
For more information about setting these values during create, see the Azure Database for PostgreSQL server CLI
Quickstart.
The backup retention period of a server can be changed as follows:

az postgres server update --name mydemoserver --resource-group myresourcegroup --backup-retention-days 10

The preceding example changes the backup retention period of mydemoserver to 10 days.
The backup retention period governs how far back in time a point-in-time restore can be retrieved, since it's based
on backups available. Point-in-time restore is described further in the next section.

Server point-in-time restore


You can restore the server to a previous point in time. The restored data is copied to a new server, and the existing
server is left as is. For example, if a table is accidentally dropped at noon today, you can restore to the time just
before noon. Then, you can retrieve the missing table and data from the restored copy of the server.
To restore the server, use the Azure CLI az postgres server restore command.
Run the restore command
To restore the server, at the Azure CLI command prompt, enter the following command:

az postgres server restore --resource-group myresourcegroup --name mydemoserver-restored --restore-point-in-


time 2018-03-13T13:59:00Z --source-server mydemoserver

The az postgres server restore command requires the following parameters:

SETTING SUGGESTED VALUE DESCRIPTION

resource-group myresourcegroup The resource group where the source


server exists.

name mydemoserver-restored The name of the new server that is


created by the restore command.

restore-point-in-time 2018-03-13T13:59:00Z Select a point in time to restore to. This


date and time must be within the
source server's backup retention period.
Use the ISO8601 date and time format.
For example, you can use your own
local time zone, such as
2018-03-13T05:59:00-08:00 . You can
also use the UTC Zulu format, for
example, 2018-03-13T13:59:00Z .

source-server mydemoserver The name or ID of the source server to


restore from.

When you restore a server to an earlier point in time, a new server is created. The original server and its databases
from the specified point in time are copied to the new server.
The location and pricing tier values for the restored server remain the same as the original server.
After the restore process finishes, locate the new server and verify that the data is restored as expected.
The new server created during a restore does not have the firewall rules that existed on the original server. Firewall
rules need to be set up separately for this new server.

Geo restore
If you configured your server for geographically redundant backups, a new server can be created from the backup
of that existing server. This new server can be created in any region that Azure Database for PostgreSQL is
available.
To create a server using a geo redundant backup, use the Azure CLI az postgres server georestore command.

NOTE
When a server is first created it may not be immediately available for geo restore. It may take a few hours for the necessary
metadata to be populated.

To geo restore the server, at the Azure CLI command prompt, enter the following command:

az postgres server georestore --resource-group myresourcegroup --name mydemoserver-georestored --source-server


mydemoserver --location eastus --sku-name GP_Gen4_8

This command creates a new server called mydemoserver-georestored in East US that will belong to
myresourcegroup. It is a General Purpose, Gen 4 server with 8 vCores. The server is created from the geo-
redundant backup of mydemoserver, which is also in the resource group myresourcegroup
If you want to create the new server in a different resource group from the existing server, then in the
--source-server parameter you would qualify the server name as in the following example:

az postgres server georestore --resource-group newresourcegroup --name mydemoserver-georestored --source-


server "/subscriptions/$<subscription ID>/resourceGroups/$<resource group
ID>/providers/Microsoft.DBforPostgreSQL/servers/mydemoserver" --location eastus --sku-name GP_Gen4_8

The az postgres server georestore command requies the following parameters:

SETTING SUGGESTED VALUE DESCRIPTION

resource-group myresourcegroup The name of the resource group the


new server will belong to.

name mydemoserver-georestored The name of the new server.

source-server mydemoserver The name of the existing server whose


geo redundant backups are used.

location eastus The location of the new server.

sku-name GP_Gen4_8 This parameter sets the pricing tier,


compute generation, and number of
vCores of the new server. GP_Gen4_8
maps to a General Purpose, Gen 4
server with 8 vCores.
IMPORTANT
When creating a new server by a geo restore, it inherits the same storage size and pricing tier as the source server. These
values cannot be changed during creation. After the new server is created, its storage size can be scaled up.

After the restore process finishes, locate the new server and verify that the data is restored as expected.
The new server created during a restore does not have the firewall rules that existed on the original server. Firewall
rules need to be set up separately for this new server.

Next steps
Learn more about the service's backups.
Learn more about business continuity options.
Migrate your PostgreSQL database using dump and
restore
7/23/2018 • 2 minutes to read • Edit Online

You can use pg_dump to extract a PostgreSQL database into a dump file and pg_restore to restore the PostgreSQL
database from an archive file created by pg_dump.

Prerequisites
To step through this how -to guide, you need:
An Azure Database for PostgreSQL server with firewall rules to allow access and database under it.
pg_dump and pg_restore command-line utilities installed
Follow these steps to dump and restore your PostgreSQL database:

Create a dump file using pg_dump that contains the data to be loaded
To back up an existing PostgreSQL database on-premises or in a VM, run the following command:

pg_dump -Fc -v --host=<host> --username=<name> --dbname=<database name> > <database>.dump

For example, if you have a local server and a database called testdb in it

pg_dump -Fc -v --host=localhost --username=masterlogin --dbname=testdb > testdb.dump

IMPORTANT
Copy the backup files to an Azure blob/store and perform the restore from there, which should be a lot faster than
performing the restore across the Internet.

Restore the data into the target Azure Database for PostrgeSQL using
pg_restore
Once you have created the target database, you can use the pg_restore command and the -d, --dbname parameter
to restore the data into the target database from the dump file.

pg_restore -v --no-owner –-host=<server name> --port=<port> --username=<user@servername> --dbname=<target


database name> <database>.dump

Including the --no-owner parameter causes all objects created during the restore to be owned by the user specified
with --username. For more information, see the official PostgreSQL documentation on pg_restore.
NOTE
If your PostgreSQL server requires SSL connections (on by default in Azure Database for PostgreSQL servers), set an
environment variable PGSSLMODE=require so that the pg_restore tool connects with SSL. Without SSL, the error may read
FATAL: SSL connection is required. Please specify SSL options and retry.

In the Windows command line, run the command SET PGSSLMODE=require before running the pg_restore command. In
Linux or Bash run the command export PGSSLMODE=require before running the pg_restore command.

In this example, restore the data from the dump file testdb.dump into the database mypgsqldb on target server
mydemoserver.postgres.database.azure.com.

pg_restore -v --no-owner --host=mydemoserver.postgres.database.azure.com --port=5432 --


username=mylogin@mydemoserver --dbname=mypgsqldb testdb.dump

Next steps
To migrate a PostgreSQL database using export and import, see Migrate your PostgreSQL database using
export and import.
For more information about migrating databases to Azure Database for PostgreSQL, see the Database
Migration Guide.
Migrate your PostgreSQL database using export
and import
6/4/2018 • 2 minutes to read • Edit Online

You can use pg_dump to extract a PostgreSQL database into a script file and psql to import the data into the
target database from that file.

Prerequisites
To step through this how -to guide, you need:
An Azure Database for PostgreSQL server with firewall rules to allow access and database under it.
pg_dump command-line utility installed
psql command-line utility installed
Follow these steps to export and import your PostgreSQL database.

Create a script file using pg_dump that contains the data to be loaded
To export your existing PostgreSQL database on-premises or in a VM to a sql script file, run the following
command in your existing environment:

pg_dump –-host=<host> --username=<name> --dbname=<database name> --file=<database>.sql

For example, if you have a local server and a database called testdb in it:

pg_dump --host=localhost --username=masterlogin --dbname=testdb --file=testdb.sql

Import the data on target Azure Database for PostgreSQL


You can use the psql command line and the --dbname parameter (-d) to import the data into the Azure Database
for PostgreSQL server and load data from the sql file.

psql --file=<database>.sql --host=<server name> --port=5432 --username=<user@servername> --dbname=<target


database name>

This example uses psql utility and a script file named testdb.sql from previous step to import data into the
database mypgsqldb on the target server mydemoserver.postgres.database.azure.com.

psql --file=testdb.sql --host=mydemoserver.database.windows.net --port=5432 --username=mylogin@mydemoserver


--dbname=mypgsqldb

Next steps
To migrate a PostgreSQL database using dump and restore, see Migrate your PostgreSQL database using
dump and restore.
For more information about migrating databases to Azure Database for PostgreSQL, see the Database
Migration Guide.
Minimal-downtime migration to Azure Database for
PostgreSQL
6/21/2018 • 2 minutes to read • Edit Online

You can perform PostgreSQL migrations to Azure Database for PostgreSQL with minimal downtime by using the
newly introduced continuous sync capability for the Azure Database Migration Service (DMS ). This
functionality limits the amount of downtime that is incurred by the application.

Overview
DMS performs an initial load of your on-premises to Azure Database for PostgreSQL, and then continuously syncs
any new transactions to Azure while the application remains running. After the data catches up on the target Azure
side, you stop the application for a brief moment (minimum downtime), wait for the last batch of data (from the
time you stop the application until the application is effectively unavailable to take any new traffic) to catch up in
the target, and then update your connection string to point to Azure. When you are finished, your application will
be live on Azure!

DMS migration of PostgreSQL sources is currently in preview. If you would like to try out the service to migrate
your PostgreSQL workloads, sign up via the Azure DMS preview page to express your interest. Your feedback is
invaluable in helping to further improve the service.

Next steps
View the video App Modernization with Microsoft Azure, which contains a demo showing how to migrate
PostgreSQL apps to Azure Database for PostgreSQL.
Sign up for limited preview of minimal-downtime migrations of PostgreSQL to Azure Database for PostgreSQL
via the Azure DMS preview page.
Configure server parameters in Azure portal
2/27/2018 • 2 minutes to read • Edit Online

You can list, show, and update configuration parameters for an Azure Database for PostgreSQL server through the
Azure portal.

Prerequisites
To step through this how -to guide you need:
Azure Database for PostgreSQL server

Viewing and editing parameters


1. Open the Azure portal.
2. Select your Azure Database for PostgreSQL server.
3. Under the SETTINGS section, select Server parameters. The page shows a list of parameters, their values,
and descriptions.

4. Select the drop down button to see the possible values for enumerated-type parameters like
client_min_messages.
5. Select or hover over the i (information) button to see the range of possible values for numeric parameters
like cpu_index_tuple_cost.

6. If needed, use the search box to narrow down to a specific parameter. The search is on the name and
description of the parameters.
7. Change the parameter values you would like to adjust. All changes you make in a session are highlighted in
purple. Once you have changed the values, you can select Save. Or you can Discard your changes.

8. If you have saved new values for the parameters, you can always revert everything back to the default
values by selecting Reset all to default.
Next steps
Learn about:
Overview of server parameters in Azure Database for PostgreSQL
Configuring parameters using the Azure CLI
Customize server configuration parameters using
Azure CLI
2/27/2018 • 2 minutes to read • Edit Online

You can list, show, and update configuration parameters for an Azure PostgreSQL server using the Command
Line Interface (Azure CLI). A subset of engine configurations is exposed at server-level and can be modified.

Prerequisites
To step through this how -to guide, you need:
Create an Azure Database for PostgreSQL server and database by following Create an Azure Database for
PostgreSQL
Install Azure CLI 2.0 command-line interface on your machine or use the Azure Cloud Shell in the Azure
portal using your browser.

List server configuration parameters for Azure Database for


PostgreSQL server
To list all modifiable parameters in a server and their values, run the az postgres server configuration list
command.
You can list the server configuration parameters for the server mydemoserver.postgres.database.azure.com
under resource group myresourcegroup.

az postgres server configuration list --resource-group myresourcegroup --server mydemoserver

Show server configuration parameter details


To show details about a particular configuration parameter for a server, run the az postgres server configuration
show command.
This example shows details of the log_min_messages server configuration parameter for server
mydemoserver.postgres.database.azure.com under resource group myresourcegroup.

az postgres server configuration show --name log_min_messages --resource-group myresourcegroup --server


mydemoserver

Modify server configuration parameter value


You can also modify the value of a certain server configuration parameter, which updates the underlying
configuration value for the PostgreSQL server engine. To update the configuration, use the az postgres server
configuration set command.
To update the log_min_messages server configuration parameter of server
mydemoserver.postgres.database.azure.com under resource group myresourcegroup.
az postgres server configuration set --name log_min_messages --resource-group myresourcegroup --server
mydemoserver --value INFO

If you want to reset the value of a configuration parameter, you simply choose to leave out the optional --value
parameter, and the service applies the default value. In above example, it would look like:

az postgres server configuration set --name log_min_messages --resource-group myresourcegroup --server


mydemoserver

This command resets the log_min_messages configuration to the default value WARNING. For more
information on server configuration and permissible values, see PostgreSQL documentation on Server
Configuration.

Next steps
To configure and access server logs, see Server Logs in Azure Database for PostgreSQL
Configure and access server logs in the Azure portal
2/27/2018 • 2 minutes to read • Edit Online

You can configure, list, and download the Azure Database for PostgreSQL server logs from the Azure portal.

Prerequisites
To step through this how -to guide, you need:
Azure Database for PostgreSQL server

Configure logging
Configure access to the query logs and error logs.
1. Sign in to the Azure portal.
2. Select your Azure Database for PostgreSQL server.
3. Under the Monitoring section in the sidebar, select Server Logs.

4. Select the heading Click here to enable logs and configure log parameters to see the server
parameters.
5. Change the parameters that you need to adjust. All changes you make in this session are highlighted in
purple.
Once you have changed the parameters, you can click Save. Or you can Discard your changes.
6. Return to the list of logs by clicking the close button (X icon) on the Server Parameters page.

View list and download logs


Once logging begins, you can view a list of available logs and download individual log files on the Server Logs
pane.
1. Open the Azure portal.
2. Select your Azure Database for PostgreSQL server.
3. Under the Monitoring section in the sidebar, select Server Logs. The page shows a list of your log files, as
shown:
TIP
The naming convention of the log is postgresql-yyyy-mm-dd_hh0000.log. The date and time used in the file name
is the time is when the log was issued. The log files rotate every one hour or 100-MB size, whichever comes first.

4. If needed, use the search box to quickly narrow down to a specific log based on date/time. The search is on
the name of the log.

5. Download individual log files using the download button (down arrow icon) next to each log file in the
table row as shown:

Next steps
See Access Server Logs in CLI to learn how to download logs programmatically.
Learn more about Server Logs in Azure DB for PostgreSQL.
For more information about the parameter definitions and PostgreSQL logging, see the PostgreSQL
documentation on Error Reporting and Logging.
Configure and access server logs by using Azure CLI
3/23/2018 • 2 minutes to read • Edit Online

You can download the PostgreSQL server error logs by using the command-line interface (Azure CLI). However,
access to transaction logs isn't supported.

Prerequisites
To step through this how -to guide, you need:
Azure Database for PostgreSQL server
The Azure CLI 2.0 command-line utility or Azure Cloud Shell in the browser

Configure logging for Azure Database for PostgreSQL


You can configure the server to access query logs and error logs. Error logs can have auto-vacuum, connection,
and checkpoint information.
1. Turn on logging.
2. To enable query logging, update log_statement and log_min_duration_statement.
3. Update retention period.
For more information, see Customizing server configuration parameters.

List logs for Azure Database for PostgreSQL server


To list the available log files for your server, run the az postgres server-logs list command.
You can list the log files for server mydemoserver.postgres.database.azure.com under the resource group
myresourcegroup. Then direct the list of log files to a text file called log_files_list.txt.

az postgres server-logs list --resource-group myresourcegroup --server mydemoserver > log_files_list.txt

Download logs locally from the server


With the az postgres server-logs download command, you can download individual log files for your server.
Use the following example to download the specific log file for the server
mydemoserver.postgres.database.azure.com under the resource group myresourcegroup to your local
environment.

az postgres server-logs download --name 20170414-mydemoserver-postgresql.log --resource-group myresourcegroup


--server mydemoserver

Next steps
To learn more about server logs, see Server logs in Azure Database for PostgreSQL.
For more information about server parameters, see Customize server configuration parameters using Azure
CLI.
Use the Azure portal to set up alerts on metrics for
Azure Database for PostgreSQL
2/27/2018 • 2 minutes to read • Edit Online

This article shows you how to set up Azure Database for PostgreSQL alerts using the Azure portal. You can
receive an alert based on monitoring metrics for your Azure services.
The alert triggers when the value of a specified metric crosses a threshold you assign. The alert triggers both
when the condition is first met, and then afterwards when that condition is no longer being met.
You can configure an alert to do the following actions when it triggers:
Send email notifications to the service administrator and co-administrators.
Send email to additional emails that you specify.
Call a webhook.
You can configure and get information about alert rules using:
Azure portal
PowerShell
Command-line interface (CLI)
Azure Monitor REST API

Create an alert rule on a metric from the Azure portal


1. In the Azure portal, select the Azure Database for PostgreSQL server you want to monitor.
2. Under the Monitoring section of the sidebar, select Alert rules as shown:

3. Select Add metric alert (+ icon).


4. The Add rule page opens as shown below. Fill in the required information:
SETTING DESCRIPTION

Name Provide a name for the alert rule. This value is sent in the
alert notification email.

Description Provide a short description of the alert rule. This value is


sent in the alert notification email.

Alert on Choose Metrics for this kind of alert.


SETTING DESCRIPTION

Subscription This field is prepopulated with the subscription that hosts


your Azure Database for PostgreSQL.

Resource group This field is prepopulated with the resource group of your
Azure Database for PostgreSQL.

Resource This field is prepopulated with the name of your Azure


Database for PostgreSQL.

Metric Select the metric that you want to issue an alert for. For
example, Storage percentage.

Condition Choose the condition for the metric to be compared with.


For example, Greater than.

Threshold Threshold value for the metric, for example 85 (percent).

Period The period of time that the metric rule must be satisfied
before the alert triggers. For example, Over the last 30
minutes.

Based on the example, the alert looks for Storage percentage above 85% over a 30-minute period. That
alert triggers when the average Storage percentage has been above 85% for 30 minutes. Once the first
trigger occurs, it triggers again when the average Storage percentage is below 85% over 30 minutes.
5. Choose the notification method you want for the alert rule.
Check Email owners, contributors, and readers option if you want the subscription administrators and
co-administrators to be emailed when the alert fires.
If you want additional emails to receive a notification when the alert fires, add them in the Additional
administrator email(s) field. Separate multiple emails with semi-colons -
email@contoso.com;email2@contoso.com
Optionally, provide a valid URI in the Webhook field if you want it called when the alert fires.
6. Select OK to create the alert.
Within a few minutes, the alert is active and triggers as previously described.

Manage your alerts


Once you have created an alert, you can select it and do the following actions:
View a graph showing the metric threshold and the actual values from the previous day relevant to this alert.
Edit or Delete the alert rule.
Disable or Enable the alert, if you want to temporarily stop or resume receiving notifications.

Next steps
Learn more about configuring webhooks in alerts.
Get an overview of metrics collection to make sure your service is available and responsive.
Create and manage Azure Database for PostgreSQL
VNet service endpoints and VNet rules by using the
Azure portal
6/4/2018 • 2 minutes to read • Edit Online

Virtual Network (VNet) services endpoints and rules extend the private address space of a Virtual Network to your
Azure Database for PostgreSQL server. For an overview of Azure Database for PostgreSQL VNet service
endpoints, including limitations, see Azure Database for PostgreSQL Server VNet service endpoints. VNet service
endpoints are available in public preview in all supported regions for Azure Database for PostgreSQL.

NOTE
Support for VNet service endpoints is only for General Purpose and Memory Optimized servers.

Create a VNet rule and enable service endpoints in the Azure portal
1. On the PostgreSQL server page, under the Settings heading, click Connection Security to open the
Connection Security pane for Azure Database for PostgreSQL. Next, click on + Adding existing virtual
network. If you do not have an existing VNet you can click + Create new virtual network to create one.
See Quickstart: Create a virtual network using the Azure portal

2. Enter a VNet rule name, select the subscription, Virtual network and Subnet name and then click Enable.
This automatically enables VNet service endpoints on the subnet using the Microsoft.SQL service tag.
IMPORTANT
It is highly recommended to read this article about service endpoint configurations and considerations before
configuring service endpoints. Virtual Network service endpoint: A Virtual Network service endpoint is a subnet
whose property values include one or more formal Azure service type names. VNet services endpoints use the
service type name Microsoft.Sql, which refers to the Azure service named SQL Database. This service tag also
applies to the Azure SQL Database, Azure Database for PostgreSQL and MySQL services. It is important to note
when applying the Microsoft.Sql service tag to a VNet service endpoint it configures service endpoint traffic for all
Azure Database services, including Azure SQL Database, Azure Database for PostgreSQL and Azure Database for
MySQL servers on the subnet.

3. Once enabled, click OK and you will see that VNet service endpoints are enabled along with a VNet rule.

Next steps
Similarly, you can script to Enable VNet service endpoints and create a VNET rule for Azure Database for
PostgreSQL using Azure CLI.
For help in connecting to an Azure Database for PostgreSQL server, see Connection libraries for Azure
Database for PostgreSQL
Create and manage Azure Database for PostgreSQL
VNet service endpoints using Azure CLI
6/4/2018 • 5 minutes to read • Edit Online

Virtual Network (VNet) services endpoints and rules extend the private address space of a Virtual Network to
your Azure Database for PostgreSQL server. Using convenient Azure Command Line Interface (CLI) commands,
you can create, update, delete, list, and show VNet service endpoints and rules to manage your server. For an
overview of Azure Database for PostgreSQL VNet service endpoints, including limitations, see Azure Database for
PostgreSQL Server VNet service endpoints. VNet service endpoints are available in public preview in all
supported regions for Azure Database for PostgreSQL.

Prerequisites
To step through this how -to guide, you need:
Install Azure CLI 2.0 command-line utility or use the Azure Cloud Shell in the browser.
An Azure Database for PostgreSQL server and database.

NOTE
Support for VNet service endpoints is only for General Purpose and Memory Optimized servers.

Configure Vnet service endpoints for Azure Database for PostgreSQL


The az network vnet commands are used to configure Virtual Networks.
If you don't have an Azure subscription, create a free account before you begin.

Open Azure Cloud Shell


Azure Cloud Shell is a free, interactive shell that you can use to run the steps in this article. Common Azure tools
are preinstalled and configured in Cloud Shell for you to use with your account. Just select the Copy button to
copy the code, paste it in Cloud Shell, and then press Enter to run it. There are a few ways to open Cloud Shell:

Select Try It in the upper-right corner of a code block.

Open Cloud Shell in your browser.

Select the Cloud Shell button on the menu in the upper-right


corner of the Azure portal.

If you choose to install and use the CLI locally, this article requires that you are running the Azure CLI version 2.0
or later. To see the version installed, run the az --version command. If you need to install or upgrade, see Install
Azure CLI 2.0.
If you are running the CLI locally, you need to log in to your account using the az login command. Note the id
property from the command output for the corresponding subscription name.

az login

Install the CLI extension for Azure Database for PostgreSQL VNet service endpoints using the
az extension add --name rdbms-vnet command.

az extension add --name rdbms-vnet

Run the az extension list command to verify the installation of the CLI extension.

az extension list

The output of the command lists all installed extensions. The Azure Database for PostgreSQL CLI extension is:
{ "extensionType": "whl", "name": "rdbms-vnet", "version": "10.0.0" }

NOTE
To uninstall the CLI extension run the az extension remove -n rdbms-vnet command.

If you have multiple subscriptions, choose the appropriate subscription in which the resource should be billed.
Select the specific subscription ID under your account using az account set command. Substitute the id property
from the az login output for your subscription into the subscription id placeholder.
The account must have the necessary permissions to create a virtual network and service endpoint.
Service endpoints can be configured on virtual networks independently, by a user with write access to the virtual
network.
To secure Azure service resources to a VNet, the user must have permission to
"Microsoft.Network/JoinServicetoaSubnet" for the subnets being added. This permission is included in the built-in
service administrator roles, by default and can be modified by creating custom roles.
Learn more about built-in roles and assigning specific permissions to custom roles.
VNets and Azure service resources can be in the same or different subscriptions. If the VNet and Azure service
resources are in different subscriptions, the resources should be under the same Active Directory (AD ) tenant, at
the time of this preview.

IMPORTANT
It is highly recommended to read this article about service endpoint configurations and considerations before running the
sample script below, or configuring service endpoints. Virtual Network service endpoint: A Virtual Network service
endpoint is a subnet whose property values include one or more formal Azure service type names. VNet services endpoints
use the service type name Microsoft.Sql, which refers to the Azure service named SQL Database. This service tag also
applies to the Azure SQL Database, Azure Database for PostgreSQL and MySQL services. It is important to note when
applying the Microsoft.Sql service tag to a VNet service endpoint it configures service endpoint traffic for all Azure
Database services, including Azure SQL Database, Azure Database for PostgreSQL and Azure Database for MySQL servers
on the subnet.

Sample script to create an Azure Database for PostgreSQL database, create a VNet, VNet service endpoint and
secure the server to the subnet with a VNet rule
In this sample script, change the highlighted lines to customize the admin username and password. Replace the
SubscriptionID used in the az account set --subscription command with your own subscription identifier.

#!/bin/bash

# To find the name of an Azure region in the CLI run this command: az account list-locations
# Substitute <subscription id> with your identifier
az account set --subscription <subscription id>

# Create a resource group


az group create \
--name myresourcegroup \
--location westus

# Create a PostgreSQL server in the resource group


# Name of a server maps to DNS name and is thus required to be globally unique in Azure.
# Substitute the <server_admin_password> with your own value.
az postgres server create \
--name mydemoserver \
--resource-group myresourcegroup \
--location westus \
--admin-user mylogin \
--admin-password <server_admin_password> \
--sku-name GP_Gen4_2

# Get available service endpoints for Azure region output is JSON


# Use the command below to get the list of services supported for endpoints, for an Azure region, say
"westus".
az network vnet list-endpoint-services \
-l westus

# Add Azure SQL service endpoint to a subnet *mySubnet* while creating the virtual network *myVNet* output is
JSON
az network vnet create \
-g myresourcegroup \
-n myVNet \
--address-prefixes 10.0.0.0/16 \
-l westus

# Creates the service endpoint


az network vnet subnet create \
-g myresourcegroup \
-n mySubnet \
--vnet-name myVNet \
--address-prefix 10.0.1.0/24 \
--service-endpoints Microsoft.SQL

# View service endpoints configured on a subnet


az network vnet subnet show \
-g myresourcegroup \
-n mySubnet \
--vnet-name myVNet

# Create a VNet rule on the sever to secure it to the subnet. Note: resource group (-g) parameter is where the
database exists. VNet resource group if different should be specified using subnet id (URI) instead of subnet,
VNet pair.
az postgres server vnet-rule create \
-n myRule \
-g myresourcegroup \
-s mydemoserver \
--vnet-name myVNet \
--subnet mySubnet

Clean up deployment
After the script sample has been run, the following command can be used to remove the resource group and all
resources associated with it.

#!/bin/bash
az group delete --name myresourcegroup
Azure Database for PostgreSQL videos
2/27/2018 • 2 minutes to read • Edit Online

Overview: Azure Database for PostgreSQL and MySQL

Azure Database for PostgreSQL and Azure Database for MySQL bring together community edition database
engines and capabilities of a fully managed service—so you can focus on your apps instead of having to manage a
database. Tune in to get a quick overview of the advantages of using the service, and see some of the capabilities in
action.
Deep dive on managed service capabilities for MySQL and PostgreSQL

Azure Database for PostgreSQL and Azure Database for MySQL bring together community edition database
engines and the capabilities of a fully managed service. Tune in to get a deep dive on how these services work—
how we ensure high availability and fast scaling (within seconds), so you can meet your customers’ needs. You'll
also learn about some of the underlying investments in security and worldwide availability.
Develop an intelligent analytics app with PostgreSQL

Azure Database for PostgreSQL brings together community edition database engine and capabilities of a fully
managed service—so you can focus on your apps instead of having to manage a database. Tune in to see in action
how easy it is to create new experiences like adding Cognitive Services to your apps by virtue of being on Azure.
How to get started with the new Azure Database for PostgreSQL service

In this video from the 2017 Microsoft //Build conference, learn from two early adopting customers how they've
used Azure Database for PostgreSQL service to innovate faster. Learn how they migrated to the service, and
discuss next steps in their application development. The video walks through some of the key service features and
discusses how you as a developer can migrate your existing applications or develop new applications that use this
managed PostgreSQL service in Azure.
Azure Database for PostgreSQL migration partners
7/17/2018 • 2 minutes to read • Edit Online

To broadly support your Azure Database for PostgreSQL solution, choose from a wide variety of industry-leading
partners and tools. This article highlights Microsoft partner companies with migration solutions supporting Azure
Database for PostgreSQL.

Migration partners
PARTNER DESCRIPTION LINKS VIDEOS

SNP Technologies Website


SNP Technologies is a cloud- Twitter
only service provider, Contact
building secure and reliable
solutions for businesses of
the future. The company
believes in generating real
value for your business.
From thought to execution,
SNP Technologies shares a
common purpose with
clients, to turn their
investment into an
advantage.

DB Best Technologies, LLC Website


DB Best helps customers get Twitter
the most out of a managed YouTube
Azure database service. The Contact
company offers several ways
for you to get started,
including Future-State
Architectural Design, Data
Management Optimization
for Microsoft Data Platform,
Microsoft Azure Deployment
Planning Services, and Azure
Data Platform Readiness
Training.

Pragmatic Works Website


Pragmatic Works is a Twitter
training and consulting YouTube
company with deep Contact
expertise in data
management and
performance, Business
Intelligence, Big Data, Power
BI, and Azure, focusing on
data optimization and
improving the efficiency of
SQL Server and cloud
management.
PARTNER DESCRIPTION LINKS VIDEOS

Infosys Website
Infosys is a global leader in Twitter
the latest digital services and YouTube
consulting. With over three Contact
decades of experience
managing the systems of
global enterprises, Infosys
expertly steers clients
through their digital journey
by enabling organizations
with an AI-powered core to
help prioritize the execution
of change. Infosys also
provides businesses with
agile digital at scale to
deliver unprecedented levels
of performance and
customer delight.

credativ Marketplace
credativ is an independent Website
consulting and services Twitter
company that since 1999 YouTube
has been offering Contact
comprehensive services and
technical support for the
implementation and
operation of Open Source
software in business
applications. Their
comprehensive range of
services includes strategic
consulting, sound technical
advice, qualified training, and
personalized support up to
24 hours per day for all your
IT needs.

Next steps
To learn more about some of Microsoft's other partners, see the Microsoft Partner site.

Anda mungkin juga menyukai