Postgre SQL PDF
Postgre SQL PDF
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
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.
3. Fill out the new server details form with the following information:
SETTING SUGGESTED VALUE DESCRIPTION
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_.
Location The region closest to your users The location that is closest to your
users.
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.)
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.
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>
--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.
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.
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:
\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.
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.
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.
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.
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.
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 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.
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.
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"
}
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.
2. Once you are connected to the server, create a blank database at the prompt.
3. At the prompt, execute the following command to switch connection to the newly created database
mypgsqldb:
\c mypgsqldb
4. In the Create - Server dialog box, on the Connection tab, fill in the settings table.
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.
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.
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.
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.
If you would just like to delete the one newly created server, you can run az postgres server delete command.
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.
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") .
cursor = conn.cursor()
# Create table
cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
print "Finished creating table"
# Cleanup
conn.commit()
cursor.close()
conn.close()
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
cursor = conn.cursor()
# 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
cursor = conn.cursor()
# 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
cursor = conn.cursor()
# 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
npm list
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
};
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
};
client.connect(err => {
if (err) throw err;
else { queryDatabase(); }
});
function queryDatabase() {
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
};
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
};
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.
import java.sql.*;
import java.util.Properties;
// 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.");
// Create table.
statement.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity
INTEGER);");
System.out.println("Created table.");
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));
}
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;
// 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.");
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
{
// 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.");
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;
// 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.");
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.
begin
# Initialize connection variables.
host = String('mydemoserver.postgres.database.azure.com')
database = String('postgres')
user = String('mylogin@mydemoserver')
password = String('<server_admin_password>')
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>')
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>')
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>')
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
// 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/>";
$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/>";
// 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>";
// 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>";
// 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>";
// 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.
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";
Console.Out.WriteLine("Opening connection");
conn.Open();
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
);
Console.Out.WriteLine("Closing connection");
conn.Close();
conn.Close();
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";
Console.Out.WriteLine("Opening connection");
conn.Open();
Console.Out.WriteLine("Closing connection");
conn.Close();
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";
Console.Out.WriteLine("Opening connection");
conn.Open();
Console.Out.WriteLine("Closing connection");
conn.Close();
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";
Console.Out.WriteLine("Opening connection");
conn.Open();
Console.Out.WriteLine("Closing connection");
conn.Close();
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
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
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 main() {
// Initialize connection string.
var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST,
USER, PASSWORD, DATABASE)
err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")
// Create table.
_, err = db.Exec("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
checkError(err)
fmt.Println("Finished creating table")
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 main() {
err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")
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 main() {
err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")
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 main() {
err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")
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.
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.
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.
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:
At the prompt, execute the following command to switch connection to the newly created database mypgsqldb.
\c mypgsqldb
You can see the newly created table in the list of tables now by typing:
\dt
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.
You can see the updated values when you retrieve the data.
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.
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 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.
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.
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"
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:
3. At the prompt, execute the following command to switch connection to the newly created database
mypgsqldb:
\c mypgsqldb
You can see the newly created table in the list of tables now by typing:
\dt
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.
You can see the updated values when you retrieve the data:
SELECT * FROM inventory;
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 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.
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.
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.
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:
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.
Functions extensions
EX TENSION DESCRIPTION
Language extensions
EX TENSION DESCRIPTION
Miscellaneous extensions
EX TENSION DESCRIPTION
pg_prewarm Provides a way to load relation data into the buffer cache.
PostGIS extensions
EX TENSION DESCRIPTION
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.
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.
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.
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.
vCores 1, 2 2, 4, 8, 16, 32 2, 4, 8, 16
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
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.
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.
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.
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
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:
Basic 1 50
Basic 2 100
When connections exceed the limit, you may receive the following error:
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:
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.
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.
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
wget http://www.openssl.org/source/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.
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
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:
postgres=>
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.
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.
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
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.
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.
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:
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.
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.
CREATE ROLE <new_user> WITH LOGIN NOSUPERUSER INHERIT CREATEDB CREATEROLE NOREPLICATION PASSWORD
'<StrongPassword!>';
CREATE ROLE <db_user> WITH LOGIN NOSUPERUSER INHERIT CREATEDB NOCREATEROLE NOREPLICATION PASSWORD
'<StrongPassword!>';
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:
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.
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
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.
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.
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.
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.
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.
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.
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.
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
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.
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:
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
Prerequisites
To complete this how -to guide, you need:
An Azure Database for PostgreSQL server and database
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.
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:
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.
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:
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:
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:
For example, if you have a local server and a database called testdb in it
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.
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.
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:
For example, if you have a local server and a database called testdb in it:
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.
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
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.
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:
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.
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
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
Name Provide a name for the alert rule. This value is sent in the
alert notification email.
Resource group This field is prepopulated with the resource group of your
Azure Database for PostgreSQL.
Metric Select the metric that you want to issue an alert for. For
example, Storage percentage.
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 protected];[email protected]
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.
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.
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.
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>
# 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
# 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
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
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.