Refer to table by id - sql

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.

Related

Can I safely drop my table from schema 1?

oracle
In schema A I created a table called "apples" with data.
In Schema B I created a copy of table "apples" from schema 1 using
create table apples as select * from schemaA.apples
My question is, now that I have schema B up and running. Can I drop/delete my schemaA.apples? There is no direct link between the tables correct?
Or if I drop schemaA.apples will schemaB.apples get runied?
There is no direct link between the tables correct?
Correct. You have two different tables, that are not related. You just copied data from one table to another at a given point in time.
Or if I drop schemaA.apples will schemaB.apples get runied?
No, there is no risk that it will impact the other table. Again, data was copied, and tables are independent.
Side note: the create table ... as select ... syntax (aka CTAS) just copies the data and the structure, but not the related objects like primary keys, constraints, indexes, sequences. You might want to check these objects, and recreate them too to the new schema.

MariaBD alternative to schema

I need to store objects in separate tables. I need to know what tables are used for what object and to avoid name collision I prefix table names with an unique UUID so I can associate each object to its tables.
The issue there is I end up with pretty long identifiers, potentially breaking the 64-character length constraint of MariaDB.
Is it possible to organize my database in a way I query something "bigger" than my table to get the tables of my object ? For example when writing JOIN statement you use tableName.columnName when duplicates can occur. Here I am looking for something like schemaName.tableName. I have not been able to find documentation on how to organize a MariaDB database in that fashion.

Joining two tables on different database servers

I need to join two tables Companies and Customers.
Companies table is in MS SQLServer and Customer table is in MySQL Server .
What is the best way to achieve this goal ?
If I am understand correctly, you need to join tables in SQL Server, not in code, because tag is sql.
If I have right, then you need to do some administrative tasks, like server linking.
Here you have an explanation how to link MySQL server into MSSQL server.
After you successfully link those servers, then your syntax is simple as:
SELECT
[column_list]
FROM companies
JOIN [server_name].[database_name].[schema_name].[table_name]
WHERE ...
Keep in mind that when accessing tables that exist on linked server, then you must write four-part names.
In order to query 2 databases, you need 2 separate connections. In this case, you would also need separate drivers, since you have a MSSQL and a MySQL database. Because you need separate connections, you need 2 separate queries. Depending on what you want to do, you can first retrieve your Companies and then do a query on Customers WHERE company = 'some value from COMPANIES' (or the other way around).
You could also just fetch every row from both tables in their own lists and compare those lists in your code, rather than using a query.
Try the following:
1 retrieve the data from Companies table from the SQL server and store the required columns in an ArrayList<HashMap<String,String>> format.
Therefore creating rows as arraylist index and HashMap as the key value pair responding to column names. Key: column name and Value as column value of that row.
2 Then pull data from Customer tables adding a where clause by converting data from your first Map into a comma separated format. Thus creating a filter similar to the join in SQL.
Add the data to the same result set data as before thus not over lapping the column names in the HashMap.
when u need to access the 5th row column7 then u write
ArrayList.get(4).get("column7");
The logic is given, Please implement it yourself.
Select Companies from DB1
Select Customers from DB2
Put them in Map<WhatToJoinOn, Company> and Map<WhatToJoinOn, Customer>
Join on map keys, creating a List<CompanyCustomer>

How to Merge Multiple Database files in SQLite?

I have multiple database files which exist in multiple locations with exactly similar structure. I understand the attach function can be used to connect multiple files to one database connection, however, this treats them as seperate databases. I want to do something like:
SELECT uid, name FROM ALL_DATABASES.Users;
Also,
SELECT uid, name FROM DB1.Users UNION SELECT uid, name FROM DB2.Users ;
is NOT a valid answer because I have an arbitrary number of database files that I need to merge. Lastly, the database files, must stay seperate. anyone know how to accomplish this?
EDIT: an answer gave me the idea: would it be possible to create a view which is a combination of all the different tables? Is it possible to query for all database files and which databases they 'mount' and then use that inside the view query to create the 'master table'?
Because SQLite imposes a limit on the number of databases that can be attached at one time, there is no way to do what you want in a single query.
If the number can be guaranteed to be within SQLite's limit (which violates the definition of "arbitrary"), there's nothing that prevents you from generating a query with the right set of UNIONs at the time you need to execute it.
To support truly arbitrary numbers of tables, your only real option is to create a table in an unrelated database and repeatedly INSERT rows from each candidate:
ATTACH DATABASE '/path/to/candidate/database' AS candidate;
INSERT INTO some_table (uid, name) SELECT uid, name FROM candidate.User;
DETACH DATABASE candidate;
Some cleverness in the schema would take care of this.
You will generally have 2 types of tables: reference tables, and dynamic tables.
Reference tables have the same content across all databases, for example country codes, department codes, etc.
Dynamic data is data that will be unique to each DB, for example time series, sales statistics,etc.
The reference data should be maintained in a master DB, and replicated to the dynamic databases after changes.
The dynamic tables should all have a column for DB_ID, which would be part of a compound primary key, for example your time series might use db_id,measurement_id,time_stamp. You could also use a hash on DB_ID to generate primary keys, use same pk generator for all tables in DB. When merging these from different DBS , the data will be unique.
So you will have 3 types of databases:
Reference master -> replicated to all others
individual dynamic -> replicated to full dynamic
full dynamic -> replicated from reference master and all individual dynamic.
Then, it is up to you how you will do this replication, pseudo-realtime or brute force, truncate and rebuild the full dynamic every day or as needed.

Difference between a db view and a lookuptable

When I create a view I can base it on multiple columns from different tables.
When I want to create a lookup table I need information from one table, for example the foreign key of an order table, to get customer details from another table. I can create a view having parameters to make sure it will get all data that I need. I could also - from what I have been reading - make a lookup table. What is the difference in this case and when should I choose for a lookup table?? I hope this ain't a bad question, I'm not very into db's yet ;).
Creating a view gives you a "live" representation of the data as it is at the time of querying. This comes at the cost of higher load on the server, because it has to determine the values for every query.
This can be expensive, depending on table sizes, database implementations and the complexity of the view definition.
A lookup table on the other hand is usually filled "manually", i. e. not every query against it will cause an expensive operation to fetch values from multiple tables. Instead your program has to take care of updating the lookup table should the underlying data change.
Usually lookup tables lend themselves to things that change seldomly, but are read often. Views on the other hand - while more expensive to execute - are more current.
I think your usage of "Lookup Table" is slightly awry. In normal parlance a lookup table is a code or reference data table. It might consist of a CODE and a DESCRIPTION or a code expansion. The purpose of such tables is to provide a lsit of permitted values for restricted columns, things like CUSTOMER_TYPE or PRIORITY_CODE. This category of table is often referred to as "standing data" because it changes very rarely if at all. The value of defining this data in Lookup tables is that they can be used in foreign keys and to populate Dropdowns and Lists Of Values.
What you are describing is a slightly different scenario:
I need information from one table, for
example the foreign key of an order
table, to get customer details from
another table
Both these tables are application data tables. Customer and Order records are dynamic. Now it is obviously valid to retrieve additional data from the Customer table to display along side the Order data, and in that sense Customer is a "lookup table". More pertinently it is the parent table of Order, because it has the primary key referenced by the foreign key on Order.
By all means build a view to capture the joining logic between Order and Customer. Such views can be quite helpful when building an application that uses the same joined tables in several places.
Here's an example of a lookup table. We have a system that tracks Jurors, one of the tables is JurorStatus. This table contains all the valid StatusCodes for Jurors:
Code: Value
WS : Will Serve
PP : Postponed
EM : Excuse Military
IF : Ineligible Felon
This is a lookup table for the valid codes.
A view is like a query.
Read this tutorial and you may find helpful info when a lookup table is needed:
SQL: Creating a Lookup Table
Just learn to write sql queries to get exactly what you need. No need to create a view! Views are not good to use in many instances, especially if you start to base them on other views, when they will kill performance. Do not use views just as a shorthand for query writing.