Inheritance MS SQL on SQL Server - sql

I have this diagram:
Where both Professional and Patient inherit from the table user.
The user id id a PK.
Professional.id and Patient.id are primary keys of their tables.
They're also FK that reference user.id.
The question here is why when I do select * from Professional I don't get the inerited column from the table User?.
I know I can join them but I thought the concept of inheritance was supposed to share the fiels from the table User in this case to the tables Professional and Patient.

To answer your question - SQL Server is not an OODBMS. Though you logically have defined a type of inheritance, the engine does not provide any direct support for including the inherited attributes in the child "class". The query "select * from table" will only include columns from the specified table. You the developer must write your queries to select the tables and columns your statement needs.

Related

What is happening under the hood when a relationship is established between tables?

This question is not limited to Power BI, but it will help me explain my problem.
If you have more than one table in Power BI, you can establish a relationship between them by dragging a column from one table to the other like this:
And you can edit that relationship by clicking the occuring line:
And by the way, here are the structures of the two tables:
# Table1
A,B
1,abc
2,def
3,ghi
4,jkl
# Table2
A,C
1,abc
1,def
2,ghi
3,ghit
This works fine since column A in Table1 consists of unique values and can work as a primary key. And now you can head over to the Report tab, set up two tables, and slice and dice at your hearts desire either by clicking directly under A in Table1, or by introducing a slicer:
But the thing is that you can do that without having established a relationship between the tables. Delete the relationshiop under Relationships and go back to Report and select Home > Manage Relationships to see what I mean:
As the dialog box says 'There are no relationships defined yet.' But you can still subset one table by making selections in the other just like before (EDIT: This statement has been proven wrong in the answer from RADO) . I do know that you can highlight the slicer and select Format > Edit Interactions and deselect the tables associated with the slicer. But I'm still puzzled by the whole thing.
So is there something happening under the hood here that I'm not aware of? Or is the relationship between tables really defined by the very contents of the tables - in the sence that the existence of related values accross tables with the existence of a potential primary key (be it natural or synthetic) makes it possible to query them using SQL, dplyr verbs or any other form of querying techniques. And that you really do not need an explicitly defined relationship?
Or put in another way, does the establishment of a Power BI table relationship have a SQL equivalent? Perhaps like the following:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
I'm sorry If I'm rambling a bit here, but I'm just very confused. And googling has so far only added to the confusion. So thank you for any insights!
Your statement "But you can still subset one table by making selections in the other just like before" is not correct. This is a key issue here.
Relations enable propagation of filter context in Power BI. That's a very loaded phrase, and you will have to learn what it means if you plan to use Power BI. It's the most important concept to understand.
To see what I mean, you will need to write DAX measures and try to manipulate them using your tables. You will immediately see the difference when you have or don't have relations.
How the whole system works (simplified):
PowerBI contains a language called "DAX". You will create measures in DAX, and PowerBI will then translate them into its internal language called xmSQL, which is a special flavor of SQL. In xmSQL, regular connection is translated into LEFT OUTER JOIN, like this:
SELECT SUM(Sales.Amount)
FROM Sales
LEFT OUTER JOIN Customer
ON Sales.Customer_Key = Customer.Customer_Key
By-directional relations are a bit more complex, but conceptually similar.
Overall, when you create relations between tables, you are telling PowerBI engine how to join the tables. The engine then also adds some optimizations to speed up the queries.
Every time you execute a DAX measure, click a slicer or a visual, PowerBI generates multiple xmSQL statements in the background, executes them, and then renders their results as visuals. You can see these SQL queries with some tools such as DAX Studio.
Note that it's not strictly necessary to establish relations between tables in PowerBI. You can imitate the same behavior using DAX (programmatically), but such "virtual" relations are more complex and can be substantially slower.
In the RM (relational model) & ERM (entity-relationship model) tables represent relation(ship)s/association. Hence, relational in "RM" & relationship in "ERM".
FKs (foreign keys) get erroneously called "relationships" in pseudo-ERM methods. A SQL FK constraint says subrows appear elsewhere as PK (primary key) or UNIQUE. A DBMS uses them to disallow invalid updates & to optimize queries.
Power BI "relationships" are not FKs. They are instructions on how to build queries.
When there is a FK we do often want to join on it. So we often want a Power BI relationship when there is a FK.
Create and manage relationships in Power BI Desktop
(See also its Download PDF link for Developer.)
PS We do not need constraints to hold or be declared or be known to query. The constraints (Including PKs, FKs, UNIQUE & cardinalities) are determined by the table meanings--(characteristic) predicates--& what business situations can arise. If constraints hold then we just sometimes get fewer rows than otherwise & some query pairs always return the same results when otherwise they wouldn't.
Foreign keys are not needed to join tables!
Is there any rule of thumb to construct SQL query from a human-readable description?
PS Cross join is inner join with a TRUE condition (or no condition in some DBMSs), period. Whether there is a "relationship" aka FK is irrelevant. If the condition is FK=PK or anything else other than TRUE then it's not a cross join; otherwise it is a cross join whether or not there is a FK between the tables. It's just that we frequently want PK=FK in a condition & tools can & do use the presence of a FK towards a default condition.
CROSS JOIN vs INNER JOIN in SQL Server 2008
You asked "What is happening under the hood?"
The simple answer is "Statements about relationships."
Many well meaning people draw ER diagrams and seem to either forget or be unaware of the fact that their ER diagrams are really "pictures of statements in language."
The problem is ambiguity.
Many well meaning people jump straight to ER diagrams without also expressing the logical statements on which their ER diagrams are based. In effect, this means that the person who draws the ER diagram seems to expect that the "reader" of the ER diagram will be able reconstruct the statements from which the ER diagram was drawn.
Here is an example to illustrate what I mean. My purpose is to show the linguistic basis of the "under the covers" relationship between Students and their Addresses.
So, what's under the covers is language!
A simple diagram
The statements from which the diagram is derived.
A more complex diagram
The statements from which the diagram is derived.

Refer to table by id

Is there a way to reference a table by id. Essentially, the table contains rows which pertain to one of many tables.
e.g. I need to reference tables A or B or C in table D's rows so that I know which table to join on.
I assume that if there is no shorthand way to reference a table externally then the only option is to store the table's name.
There is a "shorthand reference" for a table: the object identifier - the OID of the catalog table pg_class. Simple way to get it:
SELECT 'schema_name.tbl_name'::regclass
However, do not persist this in your user tables. OIDs of system tables are not stable across dump / restore cycles.
Also, plain SQL statements do not allow to parameterize table names. So you'll have to jump through hoops to use your idea in queries. Either dynamic SQL or multiple LEFT JOINs with CASE statements ... potentially expensive.

Many to many relationship self join SQL Server 2008

Are there any hard and fast rules against creating a junction table out of a table's primary key? Say I have a table with a structure similar to:
In this instance there are a list of items that can be sold together, but should be marked as dangerous. Any one item can have multiple other items with which it is dangerous. All of the items are uniquely identified using their itemId. Is it OK to refer a table to itself in a many-to-many relationship? I've seen other examples on SO, but they weren't SQL specific really.
This is the correct design for your problem, as long as your combinations can only be two-item combos.
In database design a conceptual design that renders a relation in many-to-many form is converted into 2 one-to-many in physical design. Say for example a Student could take one or many courses and a course could have many students, so that's many to many. So, in actual design it would be a Student table, Course table then CourseTaken table that has both the primary key of Student and Course table thus creating 2 one to many relayionship. In your case altough the two tables are one and the same but you have the virtual third table to facilitate the 2 one to many relationship so that to me is still very viable approach.

Inheritance with Hibernate

I need some advice on modelling my data tables. I need to apply inheritance hierarchy on my tables using SQL Server and Hibernate. Could anyone show me a basic example? It could be a tutorial on website too.
Cheers...
Set up the tables so that the derived table shares primary key with base table.
MS SQL Server isn't an object-orientated database, it is a relational database. It sounds like you should be using views over your base tables rather than duplicating columns.
Duplicating columns is unnecessary and would no doubt impact performance and maintenance would become a nightmare.
Maybe edit your question to include more details on what you are trying to achieve.
Another way is to duplicate attributes in child tables and make parent table as VIEW (that selects by common attributes from all children).
CREATE VIEW Parent
AS
SELECT ID, Name FROM Child1
UNION ALL
SELECT ID, Name FROM Child2 ...
The problem could be with ID that should be unique through all the child tables (using GUIDs is preferrable)

SQL Tables: Store references to an unknown number of rows in table A in a single record in table B

I have a table of People, and a table of Service Tickets. Service Tickets refer to 1+ People, and over time People are likely to be associated with multiple Tickets. What is the best way to represent this relationship in a SQL database?
It seems like my two options are to create 'enough' columns to contain all the person id's i should need, or a single huge string column that is processed CSV style after being fetched from the database. Both of these options have a maximum capacity, which seems like a bad design, and the second design means we can't join using the person id's.
A little background - I'm implementing a fairly small database as part of the backend for a class project. I've never really worked with SQL and what I know is self taught.
I feel like this is has to be a duplicate question, but I'm unable to find anything similar.
No, if this si a MANY to MANY relation ship, creat the table accordingly.
Create a table, something like
PeopleServiceLink:
PersonID,
ServieTicketID,
PRIMARY KEY (PersonID, ServieTicketID)
Have a read hear at Understanding SQL: Many to Many Relationships
For many-to-many relationship generally create three tables: Tickets(id, ...), People(id,...) and join table like TicketsPeopleJoin(ticketId, peopleId)
Create a separate tickets_people table which has person_id & ticket_id columns.