How to Find Primary and Foreign Keys in a Database
In this article
When you need to understand how tables in a relational database connect, finding the primary and foreign keys is the first step. This guide shows you how to locate them using SQL queries, database management tools, and system catalog tables. You'll learn what to look for in MySQL, PostgreSQL, SQL Server, and Oracle, and how to confirm your findings.
What You'll Need
- Access to the database you're inspecting (read-only access is usually enough).
- A query tool or client (like psql, MySQL Workbench, SQL Server Management Studio, or any SQL editor).
- Knowledge of the database type and version you're using.
Step-by-Step
- Identify the database system. The exact method differs by vendor. Check if you're using MySQL, PostgreSQL, SQL Server, Oracle, or SQLite. If unsure, run a version query: for MySQL,
SELECT VERSION();; for PostgreSQL,SELECT version();; for SQL Server,SELECT @@VERSION;; for Oracle,SELECT * FROM v$version;. - List all tables in the schema. You need a complete list of tables to know where to look. Use the appropriate query:
- MySQL:
SHOW TABLES;orSELECT table_name FROM information_schema.tables WHERE table_schema = 'your_database'; - PostgreSQL:
\dtorSELECT tablename FROM pg_tables WHERE schemaname = 'public'; - SQL Server:
SELECT name FROM sys.tables; - Oracle:
SELECT table_name FROM user_tables;
- MySQL:
- Find primary keys per table. For each table, you can query the system catalog. Here are the standard queries:
- MySQL:
SELECT table_name, column_name FROM information_schema.key_column_usage WHERE table_schema = 'your_database' AND constraint_name = 'PRIMARY'; - PostgreSQL:
SELECT tc.table_name, kcu.column_name FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = 'public'; - SQL Server:
SELECT tc.TABLE_NAME, kcu.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'; - Oracle:
SELECT cols.table_name, cols.column_name FROM all_constraints cons, all_cons_columns cols WHERE cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner;
- MySQL:
- Find foreign keys. Similarly, query for constraints of type 'FOREIGN KEY' or 'R':
- MySQL:
SELECT table_name, column_name, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE table_schema = 'your_database' AND referenced_table_name IS NOT NULL; - PostgreSQL:
SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = 'public'; - SQL Server:
SELECT fk.name AS FK_name, tp.name AS parent_table, cp.name AS parent_column, tr.name AS referenced_table, cr.name AS referenced_column FROM sys.foreign_keys fk INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id INNER JOIN sys.tables tp ON fkc.parent_object_id = tp.object_id INNER JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id INNER JOIN sys.tables tr ON fkc.referenced_object_id = tr.object_id INNER JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id; - Oracle:
SELECT a.table_name, a.column_name, c_pk.table_name AS referenced_table, c_pk.column_name AS referenced_column FROM all_cons_columns a JOIN all_constraints c ON a.constraint_name = c.constraint_name JOIN all_constraints c_pk ON c.r_constraint_name = c_pk.constraint_name WHERE c.constraint_type = 'R';
- MySQL:
- Use a graphical tool if available. Many database IDEs (like DBeaver, DataGrip, or built-in tools) can display relationships visually. Look for an "ER Diagram" or "Schema" option. This often shows keys and connections without writing SQL.
- Verify by checking the table structure. Run
DESCRIBE table_name;(MySQL) or\d table_name(PostgreSQL) to see column constraints. Primary keys often show as "PRI" or "PK", and foreign keys as "MUL" or "FK". - Document your findings. Write down the table names, column names, and the relationships. This helps when you need to query across tables or debug join issues.
Common Mistakes
- Assuming a column named "id" is always the primary key. It often is, but not always. A table might have a composite key or a natural key.
- Confusing unique constraints with primary keys. A unique constraint ensures uniqueness but doesn't make the column a primary key. Primary keys also imply uniqueness but are the table's identifier.
- Forgetting about composite keys. A primary or foreign key can consist of multiple columns. Your query should return all columns in the key, not just one.
- Using the wrong schema name. In PostgreSQL and MySQL, you must specify the correct schema/database name. If you omit it, you might get empty results or errors.
- Not checking for foreign keys that are not enforced. Some databases allow you to define a foreign key without enforcing it. These might not show up in constraint queries.
Tips
- Start with
information_schemafor MySQL and PostgreSQL—it's standardized and easier to read. - For SQL Server, the system views like
sys.foreign_keysare more reliable than INFORMATION_SCHEMA for complex cases. - If you're working with a large database, filter by table name to narrow down results.
- Use aliases in your queries to make the output clear, especially when joining system tables.
- If you have access to a GUI, use it to cross-check your SQL results. Visual diagrams often reveal relationships you might miss.
Troubleshooting
- Query returns no rows. Check that you're connected to the correct database/schema. Also verify that the table names are spelled correctly and that you have permission to view system catalogs.
- Permission denied errors. Some users don't have access to system tables. Ask your DBA for read-only access to the appropriate catalog views, or use a GUI that might have different permissions.
- Results are too many or too few. If you see more rows than expected, you might be querying across all schemas. Add a schema filter. If you see fewer, you might be missing tables that use non-standard naming.
- Foreign key references not showing. Some databases don't enforce foreign keys (like SQLite by default). Check the table definition directly to see if there's a REFERENCES clause.
- Confusing output. If the columns aren't clear, add column aliases or select specific columns like
table_nameandcolumn_nameonly.
Frequently Asked Questions
Can I find primary and foreign keys without writing SQL?
Yes. Most database management tools (like MySQL Workbench, pgAdmin, or DBeaver) have visual schema diagrams. Right-click a table and choose "Show Schema" or "ER Diagram" to see keys and relationships.
What if the database doesn't have any foreign keys defined?
That's possible, especially in legacy databases. You can still infer relationships by looking for columns that share the same name and data type as a primary key in another table. However, this is only a guess.
How do I find a primary key for a specific table quickly?
Use SHOW KEYS FROM table_name WHERE Key_name = 'PRIMARY'; in MySQL, or \d table_name in PostgreSQL to see the table's structure including constraints.
Are primary keys always indexed?
Yes, by definition a primary key creates a unique index to enforce uniqueness and speed up lookups. This is true in all major relational databases.
Can a foreign key reference a non-primary key column?
Technically, a foreign key must reference a column that has a unique constraint or is a primary key. In practice, it's almost always the primary key of the referenced table.
What's the difference between a primary key and a unique key?
A primary key uniquely identifies each row and cannot be NULL. A unique key also ensures uniqueness but allows one NULL value (in most databases) and can be used for other purposes like indexing.