DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
FREEDOM251

Freedom251 › Blog › Command Line

How to List Databases in PostgreSQL From the Command Line

By Freedom251 Team · · 10 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The quickest interactive method is l (or its long form, list) inside psql. From an operating-system shell, run psql -l or psql --list to connect, print the databases, and exit. If you need a SQL query for automation or custom filtering, connect to any database and run SELECT datname FROM pg_database ORDER BY datname;.

Three ways to list PostgreSQL databases

PostgreSQL stores databases at the cluster level, so you can inspect the complete set without opening each database individually. The right command depends on where you are working and how much control you need over the output.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Method Best use What it provides What you need
l or list Interactive inspection in an existing psql session A readable table with names, owners, encodings, and access privileges; optional pattern filtering An active psql connection
l+ Interactive inspection with additional database metadata The l columns plus sizes, default tablespaces, and descriptions when size visibility is permitted An active psql connection and appropriate visibility privileges for sizes
psql -l or psql --list A one-shot shell command or a script step Lists databases, then exits; accepts the normal host, port, user, and database connection options The psql client and working connection parameters
SQL on pg_database Automation, custom reports, or precise predicates Only the columns, filters, and ordering you request A connection and an SQL execution context

All four routes use PostgreSQL’s built-in client and catalog facilities; no extension is required.

Before you run a command: identify the connection context

A database list comes from a PostgreSQL server, not from the client program alone. Before troubleshooting output, establish which server, port, user, and target database the command will use.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
  • Host: -h selects a server hostname or address.
  • Port: -p selects the PostgreSQL listening port.
  • User: -U selects the database role used for authentication.
  • Database: -d selects the database to which psql initially connects.

If you omit the host, psql uses a local Unix-domain socket on systems that provide one; on Windows, the documented default is local host behavior. If you omit the user, the operating-system user name is used as the default database user. Those defaults are convenient for local administration but frequently point at a different instance than the one you intended, especially on a workstation running several PostgreSQL versions or on a machine with multiple service accounts.

The database used to establish the session is not a restriction on the catalog query: PostgreSQL’s pg_database catalog describes the databases in the cluster. For the shell listing option, psql connects to the postgres database unless you provide another database with -d or as a positional database argument.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

List databases inside an interactive psql session

Use the short meta-command

Start psql with your normal connection settings. At the psql prompt, enter:

l

The command prints the databases visible to that session in a table. The standard columns include each database name, its owner, its character-set encoding, and its access privileges. This is a psql meta-command, so it begins with a backslash and is interpreted by the client rather than sent to the server as SQL.

Use the long spelling

list is the equivalent long form:

list

Choose whichever spelling is easier for your team to recognize in runbooks. They perform the same listing operation and accept the same pattern argument.

Filter database names with a psql pattern

Append a pattern when you only want names that match a naming convention:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
l myapp*

The pattern is interpreted using psql‘s pattern rules, not as a SQL LIKE expression. If you invoke psql through a shell command or script, quote the pattern at the shell level when necessary so the shell does not expand a wildcard before psql receives it. Inside an already running psql session, enter the pattern directly after the meta-command.

A pattern is useful when a cluster contains many tenant, test, or environment databases. It keeps the interactive result focused without changing server state or requiring a separate query.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Show sizes and descriptions with l+

Add a plus sign to request the expanded database listing:

l+

The expanded display adds each database’s size, default tablespace, and description. It is the practical choice when you are investigating storage or checking whether databases are assigned to an unexpected tablespace.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Size information has a documented visibility condition. You can see it when the current role has CONNECT privilege on the database, is a superuser, or has the pg_read_all_stats role. A role may therefore see database names while receiving blank or unavailable size values. That result indicates a permission or statistics-visibility boundary; it does not mean the database disappeared.

Use the same pattern form with the expanded command when you need a filtered, detailed view:

l+ myapp*

If names appear but the added fields do not, compare the role used for the session with the visibility conditions above before changing the query.

List databases directly from the operating-system shell

Run the one-shot option

At a shell prompt, use:

psql -l

The documented long spelling is:

psql --list

Both options list all available databases and then exit. They are the shell equivalent of the interactive listing command, so they are convenient for a quick check, a deployment step, or a script that should not leave an interactive session running.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make the connection explicit

When the local defaults are not the server you want, provide the connection switches:

psql -h db.example.com -p 5432 -U report_user -l

Here, -h selects the host, -p the port, and -U the role. You can also specify the initial database explicitly:

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
psql -d postgres -l

The -d value is the database used to establish the session before the listing is requested. A positional database name is another supported way to provide that target.

Use a connection URI when that fits your environment

psql accepts a PostgreSQL connection URI as the positional connection parameter:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
psql postgresql://[email protected]/postgres -l

The URI identifies the role, host, and initial database in one argument. Keep credentials out of shell history and process listings; use the authentication mechanism approved for your environment rather than placing a password directly in a command line.

Understand what a shell failure means

If the server cannot be reached, authentication is rejected, or the role cannot establish a usable connection, psql reports the connection error and terminates. The listing operation has not partially succeeded in that situation. Correct the connection target or credentials first, then rerun the command.

Use SQL when you need a controllable result

The canonical catalog query

Connect to any database and execute:

SELECT datname
FROM pg_database
ORDER BY datname;

The essential catalog query is SELECT datname FROM pg_database;. The ORDER BY datname clause makes the result deterministic, which is preferable for human review and for scripts that compare output over time.

pg_database is a cluster-level catalog. It reports database names from the PostgreSQL cluster rather than only schemas or tables belonging to the database where your session currently resides. Consequently, switching the initial connection database does not turn this query into a per-database object listing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Include whether connections are allowed

To identify databases that have been disabled for new connections, include the catalog’s allow-connection flag:

SELECT datname, datallowconn
FROM pg_database
ORDER BY datname;

The boolean value lets an operator distinguish a normal connectable database from one intentionally marked as unavailable for new sessions.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Filter with ordinary SQL

For a SQL pattern filter, use a WHERE clause:

SELECT datname
FROM pg_database
WHERE datname LIKE 'app_%'
ORDER BY datname;

This filter uses SQL’s LIKE semantics, including its treatment of the underscore and percent characters. It is separate from the pattern syntax accepted by the l meta-command, so do not assume that a pattern copied between the two forms has identical wildcard behavior.

Why SQL is usually the automation choice

SQL lets you select exactly the columns a report needs, add predicates, and impose an ordering that remains stable. A script can therefore consume a small, purpose-built result instead of parsing the human-oriented table produced by a meta-command. Use the interactive commands when a person is inspecting a server; use the catalog query when the output is an input to another process.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choosing the right command for the task

Use l when you are already connected

If a troubleshooting or administration session is open in psql, l is the shortest path to a readable overview. Add a pattern when the cluster contains many similarly named databases. Use l+ instead when size, tablespace, or description information is part of the question and your role can see those fields.

Use psql -l for a one-time shell check

The shell option avoids entering an interactive session and exits immediately after printing the list. It is useful in a terminal checklist or a script that only needs to verify which databases are available. Supply -h, -p, -U, and -d whenever relying on implicit defaults could target the wrong instance.

Use pg_database for reports and scripts

The SQL route is the most adaptable when you need a custom column set, a naming rule, an explicit sort order, or a check such as datallowconn. It also avoids parsing presentation-oriented output. Remember that the query still requires a successful connection before it can run.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

psql: command not found

The PostgreSQL client is not installed or its executable is not on the shell’s PATH. Install the client package appropriate to your operating system, then verify the installation with:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
psql --version

Package names and installation steps differ by operating system, so use the package source maintained for your platform rather than assuming a distribution-specific command.

Connection refused, timeout, or “could not connect”

Confirm that the server is running and accepting connections, then make the target explicit:

psql -h db.example.com -p 5432 -U report_user -d postgres -l

Check the hostname, port, firewall or network route, and the server’s listening configuration. A client that points at the wrong host can produce the same symptom as a stopped server, so verify the endpoint independently.

Password prompt or authentication failure

A password prompt is normal when the server’s authentication policy requires one. An authentication error means the supplied role or credential was rejected. Use the administrator-approved PostgreSQL authentication mechanism, such as the environment’s password file or interactive prompt, and avoid embedding passwords in shell history, scripts, or process arguments.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The list contains unexpected databases

Recheck the connection context. The command may have used a local socket, the operating-system user as the database role, or the default port instead of the intended remote instance. Repeat the command with explicit -h, -p, -U, and -d values so the result can be tied to a known server and role.

Names appear, but l+ sizes are blank or unavailable

Database-name visibility and size visibility are not identical. For sizes, the current role must have CONNECT on the database, be a superuser, or hold pg_read_all_stats. Ask an administrator to confirm the role’s privileges if storage information is required; do not infer that a missing size means the database itself is absent.

The SQL query appears to show only one database

Check that you executed the cluster catalog query rather than a query against tables in the current database:

SELECT datname
FROM pg_database
ORDER BY datname;

Also verify that the session connected to the PostgreSQL cluster you intended. The catalog query returns the names associated with that cluster, so a session aimed at a different server naturally produces a different list.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A filtered result is empty

First test the unfiltered listing, then examine the pattern syntax. A l filter follows psql pattern rules, while a SQL filter follows LIKE rules. In a shell script, protect wildcard characters from shell expansion before they reach psql. Finally, check spelling, case, and the naming convention used by the databases.

Operational and security considerations

Do not confuse listing with authorization

Seeing a database name does not grant permission to connect to it or to read its contents. The listing describes what the connected role can discover through the client and catalog; access to a particular database and its objects is governed separately by PostgreSQL privileges.

Keep scripts deterministic

When another program consumes the result, include an explicit ORDER BY in the SQL query. Stable ordering prevents harmless catalog-order changes from appearing as additions or removals in generated reports. If you use the shell listing option for a human-facing log, record the explicit connection parameters alongside the command so the source instance is clear.

Use the least exposure needed

For a quick inventory, the names from l or SELECT datname ... may be sufficient. Request expanded details only when sizes, tablespaces, or descriptions answer a real operational question. Grant the additional statistics visibility required for l+ deliberately, rather than broadening privileges simply to make a display complete.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical decision sequence

  1. Already at a psql prompt? Enter l. Add a name pattern if you need to narrow the display.
  2. Need sizes, tablespaces, or descriptions? Use l+ and confirm that your role has the documented size visibility.
  3. Working from a shell or script? Run psql -l or psql --list, supplying explicit connection switches when defaults are uncertain.
  4. Need custom columns, filtering, or stable machine-readable logic? Execute an ordered query against pg_database.
  5. Any connection error? Fix the client installation, endpoint, port, authentication, or role permissions before interpreting the database list.

For most interactive administration, l is the fastest answer. For a single terminal command, psql -l is the cleanest option. For repeatable automation, query pg_database and define the exact result your process needs.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Command LineDatabase administrationPostgreSQLpsqlSQL

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.