Explain Codes LogoExplain Codes Logo

How can I get column names from a table in Oracle?

sql
database-management
oracle
sql-queries
Alex KataevbyAlex Kataev·Jan 3, 2025
TLDR

Retrieve Oracle table column names with:

SELECT column_name FROM user_tab_columns WHERE table_name = 'YOUR_TABLE';

Replace 'YOUR_TABLE' with the actual table name in uppercase. This query fetches columns for tables in your schema. For cross-schema, use all_tab_columns or dba_tab_columns if privileged.

Dive in: USER_TAB_COLUMNS

The USER_TAB_COLUMNS view houses an array of column metadata for tables you own. It’s like a personal library of tables in your schema. Let's unleash the power of USER_TAB_COLUMNS:

SELECT column_name FROM user_tab_columns WHERE table_name = 'ENTER_YOUR_TABLE_NAME_HERE';

Joke: This feels like yelling, right? Well, Oracle insists on table names being uppercase. Don't ask why, it's an Oracle thing.

When your quest for column names takes you across different schemas, remember to include the owner column:

SELECT column_name FROM all_tab_columns WHERE table_name = 'ENTER_YOUR_TABLE_NAME_HERE' AND owner = 'ENTER_SCHEMA_NAME_HERE';

Joke: It's like having a tourist visa. You can see all the beautiful column names but remember, no touching!

SQL*plus and beyond: The DESCRIBE command

Cruising through Oracle using SQL*Plus? Then you have a special command DESC at your disposal. It's a quick way to reveal a table's structure, kind of like x-ray vision!

DESC Your_Table;

Creating dynamic retrieval procedures

For those who believe in automation, there is an option to write your PL/SQL procedure. It's as if you're creating a custom spell to fetch column names whenever you need:

CREATE PROCEDURE get_column_names(p_table_name VARCHAR2) IS v_column_name all_tab_columns.column_name%TYPE; BEGIN FOR c IN (SELECT column_name FROM all_tab_columns WHERE table_name = p_table_name) LOOP DBMS_OUTPUT.PUT_LINE('Column Name: ' || c.column_name); END LOOP; END;

Joke: It's got class, it's got elegance, it's a procedure!

Presenting results in a specific order

An extra sprinkle of ORDER BY can change the game. Fetch the column names in a specific order, and witness the magic!

SELECT column_name FROM user_tab_columns WHERE table_name = 'YOUR_UPPERCASE_TABLE_NAME' ORDER BY column_id;