Home > Database > Mysql Tutorial > How to Retrieve Table Primary Keys in SQL Server and MySQL?

How to Retrieve Table Primary Keys in SQL Server and MySQL?

Susan Sarandon
Release: 2025-01-05 10:16:40
Original
222 people have browsed it

How to Retrieve Table Primary Keys in SQL Server and MySQL?

Retrieving Table Primary Keys in SQL Server

In MySQL, the following query can be used to retrieve a table's primary key:

SHOW KEYS FROM tablename WHERE Key_name = 'PRIMARY'
Copy after login

For SQL Server, there are multiple approaches to accomplish this task:

Approach 1 (Applies to SQL Server-specific Database):

Execute the following query:

SELECT COLUMN_NAME
FROM sys.primary_keys
WHERE TABLE_NAME = 'TableName'
Copy after login

Replace 'TableName' with the actual table name for which you want to retrieve the primary key.

Approach 2 (Applies to Both SQL Server and MySQL):

This query can be used to retrieve primary key information for both MySQL and SQL Server:

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'TableName'
Copy after login

Again, replace 'TableName' with the desired table name.

The above is the detailed content of How to Retrieve Table Primary Keys in SQL Server and MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template