What are the create view conditions in Oracle? - sql

I'm writing a program which is creating view with joining two tables. I have lack of information about how to join them.
When user choose two tables and their columns to be in one view, I need to join them together automatically for the user if it is possible. For this purpose I already found the code to find primary key and foreign key of tables.
With this knowledge how can I say which column of first table should join with which table of second table.
As I found information about this, Primary key of one table should join with Foreign key of another table. Is this right? Can be any other situation. I want to suggest to user that this join may work and they can modify it.

Related

Constraint Table in Postgresql Empty

I am currently working on a set of queries to pull data from a SQL table and then loop to pull any entries from other tables that are referenced in the first table through foreign keys.
aka if Table A column A can only have values that appear in Table B's primary key, I want to pull all rows of Table B referenced in my extract from Table A.
To do this in the past, I would have written a query that looks at information_schema.table_constraints and matched it against the key columns; Something like the suggested query in this article. However, when I pull the information from the table_constraints table in my current database, I get back an empty response; I get the table headers, but no rows. This is despite the fact that I know that there are many constraints, particularly foreign-key constraints, in the Postgresql database that I am using. The query giving me the empty response is as simple as possible, shown below:
SELECT * FROM information_schema.table_constraints
Is there somewhere else that I should be referencing to get the foreign key constraint information? How else can I find the foreign key constraints on a table?
EDIT: I am having a touch more luck finding things through pg_catalog; The data at least seems to exist in there. However, it is all abstracted as numerical IDs, and I am having a little trouble linking enough together to get to the actual column names and other key data.
In the information_schema views you can only see objects for which you have permissions.
You are planning to do a join, not lots of little queries by primary key, right?

SQL server tables not showing relation in Diagram

I have a lot of tables that share keys but in the diagram does not show a route from table to table. Most tables will show a route to but a lot of them do not although they should. I've already checked data types, and I can join these tables, so I am wondering if this is something I have to do within the diagram tool to set the relationships to correlating tables. I assumed this is something sql server automatically does when you select tables for the diagram.
Any suggestions?
Edited:
It could also just be that you need to "refresh" the diagram, remove and ad back the table to the diagram.
Original:
The relationship is not shown in the diagram if this does not exist. Maybe you defined they key in both tables with same name and data type but you are missing the explicit reference (constraint). Something like this:
ALTER TABLE Sales.TempSalesReason
ADD CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID)
REFERENCES Sales.SalesReason (SalesReasonID)
ON DELETE CASCADE
ON UPDATE CASCADE
;
You may want to ommit the ON [ACTION] CASCADE, though. The reason you can use JOIN in the queries is because the contraint is not mandatory in order to JOIN the tables, you can JOIN any columns as longs as the data type allows it. You can even JOIN with columns that don't have a PK, but this will have a bad performance (and is also another topic).
Refer to official documentation on how to do it with the graphic tool or with code:
https://learn.microsoft.com/en-us/sql/relational-databases/tables/create-foreign-key-relationships?view=sql-server-2016

Database design when having either foreign key or string

In my application I'm creating a case having a supervisor, but as the supervisor can be either an employee or an external supervisor, I'd like to be able to save either an employee id for the internal reference or a string for the name of the external supervisors name.
How should I implement this? Is having a table "case" and the sub-tables "case_internal_sv" and "case_external_sv" the way to go?
There's not a lot of information in your question on which to base an answer.
If there is common data and functionality across all types of supervisors then you will probably want one table to hold that common data. That table would establish the primary key values for supervisors and the case table would have a foreign key into this table. Information that is unique to either internal or external supervisors would go into separate tables and those tables would also have a foreign key back to the common supervisor level data.
This design is superior because you only have one place to go in order to find a list of all supervisors and because you can enforce the supervisor / case relationship directly in the database without a lot of code or additional constraints to ensure that "one and only one" of two columns is populated.
It's sufficiently superior, from a database point of view, that I'd consider using this design even if the data for internal and external supervisors is completely disjoint (which it's unlikely to be).
If your database allows you to define multiple primary keys you could have field employee and field employee_type combine to form the unique primary key. If not you could have an autogenerated primary key for the table and have a field for employee type and a field for employee_id.
What database are you using?
Having tables too normalized can do more harm than help. You should evaluate the benefits/drawbacks of having sub-tables based on your requirements.
A simple solution can be to have a 'sv_type' column in 'case' table. And have two columns
'internal_sv_id', a nullable foreign key to the employee table
'external_sv_name', a nullable string to save external name.
Then check for supervisor in one of these two columns based on the 'sv_type'
This design might not fully conform to 3rd normal form, but it can save lot of costly joins and allow integrity with employee table.
As for me, I'd go for the simplest solution in case of doubt.

Creating database tables regarding Primary and Foreign Keys

I'm doing an activity online where I need to create an example database for an Airline. It details the general information needed to be put into each table but I need help linking certain tables.
I've drawn up tables in Word to help me grasp the connections between tables but I'm unsure if I'm doing it correctly.
I have a table called 'Staff' that looks like this:
I was asked to create another table that provides each staff members previous work experience such as the company they worked for and join and end dates, etc.
The 'Work Experience' table:
My question is, what would be the primary key for the Work Experience table? Seeing as Staff_ID references back to the Staff table could it be both a Primary Key and a Foreign Key?
Just create a generic work_experience_id or we_id(whatever you way you want it) so that every time you want to call previous work experience for staff you just select generic id primary key.

How to best explain on what fields should a user join on?

I need to explain to somebody how they can determine what fields from multiple tables/views they should join on. Any suggestions? I know how to do it but am having difficulty trying to explain it.
One of the issues they have is they will take two fields from two tables that are the same (zip code) and join on those, when in reality they should be joining on ID columns. When they choose the wrong column to join on it increases records they receive in return.
Should I work in PK and FK somewhere?
While it is indeed typical to join a PK to an FK any conversation about JOIN clauses that only revolve around PK's and FK's is fairly limited
For example I had this FROM clause in a recent SQL answer I gave
FROM
YourTable firstNames
LEFT JOIN YourTable lastNames
ON firstnames.Name = lastNames.Name
AND lastNames.NameType =2
and firstnames.FrequencyPercent < lastNames.FrequencyPercent
The table referenced on each side of the table is the same table (a self join) and it includes three condidtions one of which is an inequality. Furthermore there would never be an FK here because its looking to join on a field, that is by design, not a Candidate Key.
Also you don't have even have to join one table to another. You can join inline queries to each other which of course can't possibly have a Key.
So in order to properly understand JOIN you just need to understand that it combines the records from two relations (tables, views, inline queries) where some conditions evaluate to true. This means you need to understand boolean logic and the database and the data in the database.
If your user is having a problem with a specific JOIN ask them to SELECT some rows from one table and also the other and then ask them under what conditions would you want to combine the rows.
You don't need to talk in terms of a primary key of a table but you should point to it and explain that it uniquely identifies a given row and that you must join to related tables using it or you could get duplicated results.
Give them examples of joining with it and joining without it.
An ER diagram showing all of the tables they use and their key relationships would help ensure that they always use the correct keys.
It sounds to me like neither you, nor the person you are trying to help understands how this particular database is constructed and perhaps don't really even understand basic database fundamentals, like PK's and FK's. Most often a PK from one table is joined to a FK to another table.
Assuming the database has the proper PK's and FK's in place, it would probably help a great deal to generate an ER diagram. That would make the joining concept much easier to grasp.
Another approach you could take is to find someone who does understand these things and create some views for this person to use. This way he doesn't need to understand how to join the tables together.
A user shouldn't typically be doing joins. A user should have an interface that lets them get the data that they need in the way that they need it. If you don't have the developer resources to do that then you're going to be stuck with this problem of having to teach a user technical details. You also need to be very careful about what kind of damage the user can do. Do they have update rights on the data? I hope they don't accidentally do a DELETE FROM Table with no WHERE clause. Even if you restrict their permissions, a poorly written query can crush the database server or block resources causing problems for other users (and more work for you).
If you have no choice, then I think that you need to certainly teach them about primary and foreign keys, even if you don't call them that. Point out that the id on your table (or whatever your PK is) identifies a row. Then explain how the id appears in other tables to show the relationship. For example, "See, in the address table we have a person_id which tells us who that address belongs to."
After that, expect to spend a large portion of your time with that user as they make mistakes or come up with other things that they want to get from the database, but which they can't figure out how to get.
From theory, and ideally, you should define primary keys on all tables, and join tables using a primary key to the matching field or fields (foreign key) in the other table.
Even if you don't define or if they're not defined as primary keys, you need to make sure the fields uniquely identify the records in the table, and that they should be properly indexed.
For example, let's say the 'person' table has a SSN and a driver's license field. The SSN could be considered and flagged as the 'primary key', but if you join that table to a 'drivers' table which might not have the SSN, but does have the driver's license #, you could join them by the driver's license field (even if it's not flagged as primary key), but you need to make sure that the field is properly indexed in both tables.
...explain to somebody how they can determine what fields from multiple tables/views they should join on.
Simply put, look for the columns with values that match between the tables/views. Preferably, match exactly but some massaging might be necessary.
The existence of foreign key constraints would help to know what matches to what, but the constraint might not be directly to the table/view that is to be joined.
The existence of a primary key doesn't mean it is the criteria that is necessary for the query, so I would overlook this detail (depending on the audience).
I would recommend attacking the desired result set by starting with the columns desired, and working back from there. If there's more than one table's columns in the result set, focus on the table whose columns should be returning distinct results first and then gradually add joins, checking the result set between each JOIN addition to confirm the results are still the same. Otherwise, need to review the JOIN or if a JOIN is actually necessary vs IN or EXISTS.
I did this when I first started out, it comes from thinking of joins as just linking tables together, so I linked at all possible points.
Once you think of joins as a way to combine AND filter the data it becomes easier to understand them.
Writing out your request as a sentence is helpful too, "I want to see all the times Table A interacted with Table B". Then build a query from that using only the ID, noting that if you wanted to know "All the times Table A was in the same zip code as Table B" then you would join by zip code.