Get Table Primary Key Column In SQL (2024)

In this blog, we will discuss how we can get the primary column name of any table programmatically. However, we can see the primary column name by just right-clicking on a table and seeing the design view. But when we have dynamically created a table and set the primary key, then we do not know the primary column name. So in this article, we discuss that.

In my database, I have only one table named Employee, and you can see in the below image the primary key column is EmployeeId.

Get Table Primary Key Column In SQL (1)

Here we use INFORMATION_SCHEMA.TABLE_CONSTRAINTS and INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE view, so first, we get what's inside that view.

Run the following queries to get the output of both views.

INFORMATION_SCHEMA.TABLE_CONSTRAINTS

select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS

Output

Get Table Primary Key Column In SQL (2)

INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE

select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE

Output

Get Table Primary Key Column In SQL (3)

How to get Primary Key Column Name Programmatically?

Here are a few lines of SQL query using which we can get the primary column name.

select C.COLUMN_NAME FROMINFORMATION_SCHEMA.TABLE_CONSTRAINTS TJOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CON C.CONSTRAINT_NAME=T.CONSTRAINT_NAMEWHEREC.TABLE_NAME='Employee'and T.CONSTRAINT_TYPE='PRIMARY KEY'

Output

Get Table Primary Key Column In SQL (4)

Explanation

  • Here we join these two views, TABLE_CONSTRAINTS And CONSTRAINT_COLUMN_USAGE on CONSTRAINT_NAME.
  • Then select those records where CONSTRAINT_COLUMN_USAGE.TABLE_NAME is Employee and TABLE_CONSTRAINTS.CONSTRAINT_TYPE is the Primary Key.
  • And then, select CONSTRAINT_COLUMN_USAGE. COLUMN_NAME.

So that is just two or three lines of SQL query for getting the primary column name of any table. I hope you find some useful information in this article. If you find this helpful, kindly share it with your friends.

I'm a seasoned database professional with extensive expertise in SQL and relational database management systems. I have hands-on experience in designing, implementing, and optimizing databases, and I've tackled various challenges related to schema design, query optimization, and dynamic table creation. My proficiency is grounded in practical application, and I've successfully addressed issues similar to the one discussed in the provided article.

In the article, the author addresses the common challenge of programmatically retrieving the primary column name of a dynamically created table. The approach outlined involves using two key views provided by the INFORMATION_SCHEMA database: TABLE_CONSTRAINTS and CONSTRAINT_COLUMN_USAGE.

  1. INFORMATION_SCHEMA.TABLE_CONSTRAINTS: The author suggests running the following query to view the contents of the TABLE_CONSTRAINTS view:

    select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS

    This view contains information about constraints defined on tables, including the type of constraint, the table name, and the constraint name.

  2. INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE: Similarly, the author recommends running the following query to inspect the CONSTRAINT_COLUMN_USAGE view:

    select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE

    This view provides details about columns associated with constraints, linking columns to their respective constraint names.

  3. Getting Primary Key Column Name Programmatically: To programmatically retrieve the primary key column name for a specific table (e.g., 'Employee'), the author provides the following SQL query:

    select C.COLUMN_NAME FROM
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS T
    JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE C ON C.CONSTRAINT_NAME=T.CONSTRAINT_NAME
    WHERE
    C.TABLE_NAME='Employee' and T.CONSTRAINT_TYPE='PRIMARY KEY'

    The query joins TABLE_CONSTRAINTS and CONSTRAINT_COLUMN_USAGE on CONSTRAINT_NAME, filters the results based on the target table name ('Employee') and constraint type ('PRIMARY KEY'), and finally selects the primary key column name.

  4. Output and Explanation: The author demonstrates sample outputs of the two views, emphasizing the joined records where the specified conditions are met. The explanation clarifies the logic behind the query, detailing the join conditions and the selection of the primary key column name.

  5. Conclusion: The article concludes with a concise summary, highlighting the efficiency of the two or three lines of SQL query for obtaining the primary column name of any table. The author encourages sharing the information if found helpful.

This comprehensive approach provides a valuable resource for developers and database administrators seeking to programmatically identify the primary key column of a dynamically created table.

Get Table Primary Key Column In SQL (2024)

FAQs

How to get primary key column name of table in MySQL? ›

To check the structure of your table, you can use the SHOW CREATE TABLE command. This will show you the column names, data types, and other information about the table including the primary key. You can also use the SHOW INDEXES command to see the indexes created by MySQL.

How to find table name from primary key in SQL? ›

If the primary key name is the first column in the table, you can just do: select table_name from information_schema. columns where column_name in (<your list here>) and ordinal_position = 1; Otherwise, you have to go through the constraints to get what you want.

Which column is primary key? ›

A primary key, also called a primary keyword, is a column in a relational database table that's distinctive for each record. It's a unique identifier, such as a driver's license number, telephone number with area code or vehicle identification number (VIN). A relational database must have only one primary key.

How do I select a primary key in SQL? ›

When selecting a primary key, you'll need to choose a column that contains unique values for all rows. Every single row must have a value in the primary key column, and the values must not change. If you can't find a natural primary key that fits all of the rules, you could create a surrogate key.

How to find the key fields in the table? ›

The key fields of a table must be located together at the beginning of the table, which means that no non-key fields are allowed between two key fields. The primary key comprising the key fields is a unique identification for a table row.

How do you determine the primary key of your table? ›

Often, a unique identification number, such as an ID number or a serial number or code, serves as a primary key in a table. For example, you might have a Customers table where each customer has a unique customer ID number. The customer ID field is the primary key.

How to see primary key of table in SQL Developer? ›

Question: How do I determine if a table has a primary key and if it has one, how do I determine what columns are in the primary key? Answer: You can retrieve primary key information with the following SQL statement: SELECT cols. table_name, cols.

How to see columns of a table in SQL? ›

You can list a table's columns with the mysqlshow db_name tbl_name command. The DESCRIBE statement provides information similar to SHOW COLUMNS .

How to check which column is primary key and foreign key in SQL? ›

Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the "Persons" table. The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

Do all SQL tables have a primary key? ›

Ideally, every table should have a Primary Key. It's very important that a table has a Primary Key. There are two good reasons why a table should have a Primary Key. First, a Primary Key uniquely identifies each record in a table so it helps to ensure against redundant data in that table.

How do I find a specific table name in SQL? ›

To search for a specific table using the information_schema view, the following query can be used: SELECT * FROM INFORMATION_SCHEMA. TABLES WHERE [TABLE_NAME] = 'Address';

How to check primary key of table in SQL Developer? ›

Question: How do I determine if a table has a primary key and if it has one, how do I determine what columns are in the primary key? Answer: You can retrieve primary key information with the following SQL statement: SELECT cols. table_name, cols.

What does a primary key look like in SQL? ›

The primary key in SQL is a single, or a group of fields or columns that can uniquely identify a row in a table. Putting it simply, it is a column that accepts unique values for each row.

How to use desc command in SQL? ›

A desc command is also called a describe command in SQL. The command is case-insensitive and can be used in any of the below forms. Desc Table_Name; The above two commands perform the same function and will produce the same result.

Top Articles
How the Internet has Helped Entertainment Evolve • Digicult | Digital Art, Design and Culture
Rates and fees
Whas Golf Card
Victor Spizzirri Linkedin
Fat People Falling Gif
Phone Number For Walmart Automotive Department
Craigslist Vermillion South Dakota
Farmers Branch Isd Calendar
Jasmine
The Wicked Lady | Rotten Tomatoes
Craigslist/Phx
Es.cvs.com/Otchs/Devoted
Miami Valley Hospital Central Scheduling
2016 Hyundai Sonata Price, Value, Depreciation & Reviews | Kelley Blue Book
Local Dog Boarding Kennels Near Me
Diablo 3 Metascore
Simon Montefiore artikelen kopen? Alle artikelen online
Payment and Ticket Options | Greyhound
Wisconsin Women's Volleyball Team Leaked Pictures
Gem City Surgeons Miami Valley South
3S Bivy Cover 2D Gen
Vintage Stock Edmond Ok
Candy Land Santa Ana
Gopher Hockey Forum
Https Paperlesspay Talx Com Boydgaming
Diakimeko Leaks
Somewhere In Queens Showtimes Near The Maple Theater
Air Quality Index Endicott Ny
About My Father Showtimes Near Copper Creek 9
Academy Sports Meridian Ms
Koninklijk Theater Tuschinski
Belledelphine Telegram
Dr. Nicole Arcy Dvm Married To Husband
Usa Massage Reviews
Greater Orangeburg
APUSH Unit 6 Practice DBQ Prompt Answers & Feedback | AP US History Class Notes | Fiveable
Pfcu Chestnut Street
The Hoplite Revolution and the Rise of the Polis
Pensacola 311 Citizen Support | City of Pensacola, Florida Official Website
2024 Ford Bronco Sport for sale - McDonough, GA - craigslist
Keeper Of The Lost Cities Series - Shannon Messenger
Best Restaurants In Blacksburg
Viewfinder Mangabuddy
Craigslist Jobs Brownsville Tx
Final Jeopardy July 25 2023
Qlima© Petroleumofen Elektronischer Laserofen SRE 9046 TC mit 4,7 KW CO2 Wächter • EUR 425,95
All Characters in Omega Strikers
Todd Gutner Salary
Pulpo Yonke Houston Tx
Texas 4A Baseball
Varsity Competition Results 2022
Latest Posts
Article information

Author: Kimberely Baumbach CPA

Last Updated:

Views: 5737

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Kimberely Baumbach CPA

Birthday: 1996-01-14

Address: 8381 Boyce Course, Imeldachester, ND 74681

Phone: +3571286597580

Job: Product Banking Analyst

Hobby: Cosplaying, Inline skating, Amateur radio, Baton twirling, Mountaineering, Flying, Archery

Introduction: My name is Kimberely Baumbach CPA, I am a gorgeous, bright, charming, encouraging, zealous, lively, good person who loves writing and wants to share my knowledge and understanding with you.