• (nodebb)

    I half-suspect that's auto-generated code. The rule says "When connecting two tables, make sure there's a FK constraint between them so there can't be orphan records". So when the dumb SQL generator code was told to connect table A to table A, it mindlessly added the appropriate FK constraint.

    But where's the fun in that? Better to think it was a clueless self-taught noob. Or more likely somebody who took, passed, but understood none of, Databases 201.

  • (nodebb) in reply to WTFGuy

    I agree on the autogenerated but I think this is probably the result of someone accidentally dragging the PK column while using a table/diagram designer like the one that has been included with SSMS since forever, the same one that produces names like PK__Configur__F6E145D05992BA46 and DF__Configura__KtCal__7F23583C.

  • Hmmmm 🤨 (unregistered)

    My mind tells me this may make sense when performing some sort of database-assisted recursion, whereby you might use the database for some amount of memoization/stack reference.

  • (nodebb)

    having a ManagerId field is a terrible choice,

    The only smart thing I've ever done is realized that I'm not as smart as I think I am, so I'll ask all y'all if my answer to the above is correct: the proper way to handle that is to have a separate mapping table with an [EmployeeID] column and a [ManagerID] column.

    Yes? No?

    Addendum 2026-11-05 09:27: . . . both of which are foreign keys to the [Employee] table.

  • klinsten1 (github) in reply to dpm

    in my opinion it is a bad thing bc having a manager is a bad thing... they're the ones responsible for having this kind of code in 99% of the cases

  • (nodebb)

    "..the proper way to handle that is to have a separate mapping table with an [EmployeeID] column and a [ManagerID] column." "having a manager is a bad thing... they're the ones responsible for having this kind of code in 99% of the cases"

    I agree, having a separate mapping table would be my choice, but that leads to the ugly possibility of not just having a manager, but having multiple managers shudder

  • (nodebb) in reply to n9ds

    @n9ds - Apparently you are young enough to have missed the "matrix management" craze of the 80s.

  • valued internet subscriber (unregistered) in reply to dpm

    Yeah I don't really agree with Remy here. I see no benefit in having a separate mapping table with two FKs back to the employee table. Maybe someone smarter than me can explain why that would be preferred.

  • (nodebb) in reply to dpm

    The only smart thing I've ever done is realized that I'm not as smart as I think I am, so I'll ask all y'all if my answer to the above is correct: the proper way to handle that is to have a separate mapping table with an [EmployeeID] column and a [ManagerID] column.

    Yes? No?

    The proper way to do that is to have a field on the employee record that points to a manager_id field in a MANAGERS table. That table has a bunch of demographic info about the management position - not the employee who is the manager - but it contains employee_id that maps back to EMPLOYEES. There should not be any foreign keys here because the person who is the Big Big Boss does not have a manager. If there is a FK constraint from EMPLOYEES.Manager_Id to MANAGERS.Manager_Id the CEO's employee record cannot be added because their Manger_Id would be null. However, there should be a FK constraint from MANAGERS.Employee_id (the employee number of the manager) back to EMPLOYEES.Employee_id so that no record can be inserted into the MANAGERS table with an invalid employee number for the manager.

    EMPLOYEES should have PK as Company, Employee_Id and MANAGERS should have PK as Company, Manager_Id. It is debatable as to whether the PK suffices as a proper constraint; I have seen situations where EMPLOYEES has a unique primary index AND a constraint defined as the exact same unique index. Whether the additional constraint is required is debatable, but they are redundant. The main difference is a PK cannot have NULL values and is a clustered index; a constraint can have one (or more, depending on the DB) NULL values and is non-clustered, taking up more space.

    Addendum 2026-11-05 11:25: EDIT: "There should not be any foreign keys here because the person who is the Big Big Boss does not have a manager."

    I meant there should not be FK constraint on the employee record to the manager table. There absolutely should be a FK constraint on the manager table's employee id back to the employee table.

  • (nodebb) in reply to n9ds

    Thinking about it, I think someone can have multiple positions at a job (not at all common, but still possible), and each position will have their own manager.

  • Foo AKA Fooo (unregistered) in reply to Bananafish

    What about a nullable FK? I know, some people dislike them, but how are they worse than no FK at all? They won't prevent you from forgetting to set the manager, but they will prevent you from setting an invalid manager_id, or deleting a manager that still manages employees.

  • (nodebb) in reply to Bananafish

    I meant there should not be FK constraint on the employee record to the manager table.

    A null value doesn't violate a foreign key. Put FK in place and simply don't fill in the manager for the top of the org chart.

  • (author) in reply to valued internet subscriber

    A slightly different reason than some of the ones discussed: employee to manager is one kind of important relationship I may want to track between employees, but is far from the only one. An employee will have a manager, but they may also have a line or production manager (who oversees their day to day work, but isn't responsible for broader assignments or broader resource planning). They may also have something like a tech lead, which maybe is like a line manager, but also might not be. One employee may be shared across multiple teams, and thus have different managers depending on the assignment. And what happens with contractors, who may be assigned to a team but have no real manager within the company?

    The key problem with putting a strict 1:many on the manager/employee relationship is that it makes some pretty naive assumptions about how your company is going to organize, and encodes that assumption into your database in a way that will be difficult to change.

    These are all real problems I've run into, and why a lot of larger ERP systems are so goddamn complicated.

  • (nodebb) in reply to Foo AKA Fooo

    What about a nullable FK? I know, some people dislike them, but how are they worse than no FK at all? They won't prevent you from forgetting to set the manager, but they will prevent you from setting an invalid manager_id, or deleting a manager that still manages employees.

    Yes, absolutely, the constraint will check that IF there is a value it must exist in a foreign table, but "anyone can type nothing" so no real check is made if the value is null.

    The key (no pun intended) to all this is balancing FK constraints with the application's data integrity checks. If the application does nothing and the database allows nullable FK, then a user can forget to enter something. But, if the application verifies this is the intention, it's a much more sane way to handle it. With my example, this allows a null value if that's what the user wants. The manager id on the employee can be null (Big Big Boss). The employee number on the manager record, however, can never be null, and it must tie back to a valid id in the employee master.

    Balancing PK, FK, and application validations is more of a science than it seems. You do not want an application to verify by query each and every one of the 50 fields on a form. You want the database to carry as much work as is practical because - trust me - it's better at this than we are. Creating dozens of constraints based on lots of conditions is feasible, but you need to keep in mind that SOME of those conditions may need to reference data values in the current record, and until it's written the database is powerless. At the same time, certain conditions might cause conflicting constraints to prevent a transaction from persisting. Here is where the application must step in and do sanity checks in addition to handling PK/FK constraint errors post-commit.

    The best advice I can give anyone is, "Know your tools and use them correctly."

  • (nodebb)

    The second best advice is "If the business rules where you work are simply a gigantic pile of seemingly random exceptions to anything remotely resembling commonplace business processes, quit. It's your only hope."

    Nuking from orbit wouldn't hurt either. But quitting is usually sufficient.

  • Foo AKA Fooo (unregistered) in reply to Bananafish

    " You want the database to carry as much work as is practical" Yes, that's why I argued for adding a (nullable FK) vs. your suggestion of no FK at all. I didn't suggest to remove anything, just adding another automatic check.

  • 516052 (unregistered) in reply to WTFGuy

    What I am hearing is do not work at any place with 2 or more people?

  • SG (unregistered)

    I've seen something like this used to enforce a singleton nature on a table... insert one row, then add a constraint that prevents that row from being deleted, or other rows from being inserted.

  • (nodebb) in reply to Baflingo

    Apparently you are young enough to have missed the "matrix management" craze of the 80s.

    These days, it's tensor management. And it sure makes me tense!

  • (nodebb) in reply to Foo AKA Fooo

    " You want the database to carry as much work as is practical" Yes, that's why I argued for adding a (nullable FK) vs. your suggestion of no FK at all. I didn't suggest to remove anything, just adding another automatic check.

    i was thinking non-nullable FK there.

  • SomeWTFname,RefreshedDaily (unregistered) in reply to Bananafish

    The PK does not need to be clustered. At least, not in MS (T-)SQL. Im pretty sure you occassionally want an unclustered PK index in certain cases. I can't remember why, but I know I had to make another index clustered instead of the PK index for reasons. Might be performance (lookups mostly using non-PK columns for example.

  • (nodebb)

    Oh how I wish I worked with an RDMS that had a concept of foreign keys :) But despite being a database engine born from the '80s and still in use today by lots of companies, it still does not have any actual concept of them at all.

    It relies on the developers using database schema triggers, indexes, and code to enforce.

    Fast and extremely powerful though it is :)

  • valued internet subscriber (unregistered) in reply to Remy Porter

    This makes sense to me from a functional perspective; use something like an employee_relationships mapping table to describe the workplace and its hierarchies if that is needed. But from a purely technical perspective, I can see no real downsides to doing it in a single table if that single relationship is all that needs to be tracked.

  • (nodebb) in reply to SomeWTFname,RefreshedDaily

    The PK does not need to be clustered. At least, not in MS (T-)SQL. Im pretty sure you occassionally want an unclustered PK index in certain cases. I can't remember why, but I know I had to make another index clustered instead of the PK index for reasons. Might be performance (lookups mostly using non-PK columns for example.

    Putting a clustered index on a PK makes inserts faster and often makes non-clustered indexes more efficient (makes the bookmarks smaller and reduces fragmentation). Putting a clustered indexes on a foreign key or a date column that is frequently used for date-range reporting is almost always better for a general-purpose, mixed-use database.

  • (nodebb)

    Does this actually do nothing, or does it make the table semi-immutable, where it's impossible to add another row because it doesn't already exist, and impossible to delete a row because it still exists, but you can still modify existing rows? Sort of like an enum...

Leave a comment on “Only Create Me if I Exist”

Log In or post as a guest

Replying to comment #706003:

« Return to Article