Open In App

SQL Query to Get Column Names From a Table

Improve
Improve
Like Article
Like
Save
Share
Report

SQL stands for Structured Query Language. It is a language used to interact with the database, i.e to create a database, to create a table in the database, to retrieve data or update a table in the database, etc. SQL is an ANSI(American National Standards Institute) standard. Using SQL, we can do many things. For example – we can execute queries, we can insert records into a table, we can update records, we can create a database, we can create a table, we can delete a table, etc. 

In this article, we will look at how to get column names from a table.

Step 1: Creating Database

We are creating the database using CREATE query.

Query:

CREATE DATABASE Test

Output:

The command is completed successfully. It means the Database named Test is created. The next step is to create a table.

Step 2: Creating table

The Data table will have three fields FirstName, LastName, and Age. Using the below query we will be creating a table.

Query:

CREATE TABLE Data(FirstName varchar(40),
LastName varchar(30),Age int, );

Output:

The Data table is created in the database.

Step 3: Insert  Data into the Table

Using the below query we will be adding the data to our table.

Query:

INSERT INTO Data
VALUES ('Rahul','Sharma',15),
   ('Soha','Shaikh',24),
   ('Vivek','Rao',18),
   ('Sonali ','Rane',20);

Output:

We have added the data to our table. We can verify the data in the table using the SELECT query as below.

Step 4: View Table Data

Query:

SELECT * FROM Data

Output:

Step 5: Getting column names from the table

We will be using sys. columns to get the column names in a table. It is a system table and used for maintaining column information. It contains the following information about columns:

  • Name – Name of the column.
  • Object_id – ID of the object for the table in which column belongs.
  • Column_id – ID of the column.
  • user_type_id – ID of the user-defined column type.
  • max_length – Maximum length of the column (In bytes).
  • is_nullable – 1=Column is nullable.

Query:

SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('Data')  

Output:


Last Updated : 10 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads