Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
Recover table name in SQL query

I think it's a stupid question but is it possible to recover tables names for each columns in a SQL Query ? Example if my query is:

Select e.empno,e.sal,d.deptno
FROM emp e JOIN dept d
ON e.deptno = d.deptno
WHERE e.job = 'Analyst'

I would like to recover something like this

+-------+---------+
| Column|  Table  |
+-------+---------+
|  empno| emp     |
|   sal | emp     |
| deptno| dept    | 
+-------+---------+

I use postgresql

Thank for help

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

When a result is set back to the client it comes without any display or formatting. I assume this question from the context of PSQL in which case you're not referring to actually getting the column names of the table, but instead to the display-format of the query result. PSQL calls this expanded display. You can enable it with \x after you start psql, or you can start psql with it using the --expanded flag.

\x
Expanded display is on.

test=# SELECT * FROM ( VALUES (1,2,3),(4,5,6) ) AS t(foo,bar,baz);
-[ RECORD 1 ]
foo | 1
bar | 2
baz | 3
-[ RECORD 2 ]
foo | 4
bar | 5
baz | 6

If you're referring to actually knowing where the columns are being sourced from in the display format you can not do that. SQL only maintains a result set. It does not know where the table that originated the data is.

And, that wouldn't make much sense anyway, what would this show...

SELECT *
FROM (
  SELECT a
  FROM foo
) AS t;

Would it show the table as t or a?

What about this...

SELECT a+1 AS b, 'b' AS a
FROM (
  SELECT a
  FROM foo
) AS t;

You can see that getting silly really fast.

over 4 years ago · Santiago Trujillo Report

0

Will aliases meet your requirement?

Select e.empno "emp empno"
,e.sal "emp sal"
,d.deptno "dept deptno"

FROM emp e JOIN dept d ON e.deptno = d.deptno
WHERE e.job = 'Analyst'
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!