2

I can alias a table name in a Postgres statement like this:

SELECT a.id FROM very_long_table_name AS a;

Is there a mechanism to set up a similar alias that persists for a psql session?

For example:

$: psql -d sample
sample=# CREATE ALIAS a for very_long_table_name;
sample=# select id from a limit 1;
 id 
____
  1

3 Answers 3

3

As shown in the manual this can be done using psql variables:

sample=# \set a 'very_long_table_name'
sample=# select id from :a limit 1;
 id 
----
   1
(1 row)

If you don't want to run \set every time manually, you can include your common short names in ~/.psqlrc which is read when you start psql

Sign up to request clarification or add additional context in comments.

Comments

1

I don't know of a way to create such an alias, but you may create a view on top of your table, and give it a short name, e.g.

CREATE VIEW short_name AS
SELECT *
FROM very_long_table_name;

Then, use the view name as you would the alias. Since views generally perform as well as the underlying tables, with regard to indices, you should not lose much in terms of performance.

Comments

1

I think the best option is to create a temporary view.

This solution is not restricted to psql.

CREATE TABLE averylongname (id integer PRIMARY KEY);
INSERT INTO averylongname VALUES (1);

CREATE TEMPORARY VIEW x AS SELECT * FROM averylongname;

The view will automatically vanish when your database session ends, and it can be used with DML statements as well:

INSERT INTO x VALUES (2);
SELECT * FROM x;

 id 
----
  1
  2
(2 rows)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.