oracle sql : selecting fields from two views with no field overlap - sql

Working in Oracle SQL Developer (3.2.20.09).
I have to create a view from two source views. For example, Fields 1-3 exist in View A and Fields 4-6 exist in View B. There is zero overlap. I cannot select both views and pull all their fields into a subsequent view because combined they have too many fields (the two source views have combined well over the total fields allowed in a single view).
Is it possible to tell my pl/sql package procedure: get this field from view A. If it's not there, go to view B?
Or is a better solution to use all_tab_columns or some other meta(?) solution, look to see who owns Field 1 and grab it from there?
I don't have any experience with either of the above two options so would appreciate a lot of guidance.
Or is there simply a better third option?

It's not possible to create a view with more than 1000 columns. If the combined number of columns of your view A and B is less, you can simply create a third view using SQL in a worksheet:
CREATE OR REPLACE VIEW view_3 (f1, f2, f3, f4, f5, f6)
AS
SELECT a1, a2, a3, NULL, NULL, NULL FROM view_a UNION ALL
SELECT null, null, null, b4, b5, b6 FROM view_b;

Related

create a table with a Boolean column generated based on other tables columns values?

I have tables A, B, C with millions of rows each. Tables B and C reference table A. The tables are mainly used for one query with multiple filters but only one of those filters vary between queries. since the constant parameters are adding significant time to the query execution time, I was wondering if there is a way to precompute these params into a new table. I was looking at materialized views but the issue is that the computed type I want will be different from the original column type. To explain I will give an example.
lets say these tables represent a book store database. Table A contains general information and table B contain multiple codes for each book to indicate what categories they fall under such as 406, 678, 252.. . I'm building a query to search for books that only fall under 3 of those categories. The variable here is the keyword search in the discreption of the book. I will always need books under those 3 categories (codes) so these are constants.
What I want to do is create a table where it will have a column that tells me whether a given serial falls under those 3 codes or not. this can be done with a boolean type. I don't want to have to join these table and filter for these 3 codes (and more in the real scenario) for every query.. As I understand materialized views can't have generated fields?
What do you think is a good solution here?
You have multiple options.
Partial Index
PostgreSQL allows you to create an index with a where clause like so:
create index tableb_category on tableb (category)
where category in (406, 678, 252);
Create a view for those categories:
create view v_books_of_interest
as
select tablea.*, tableb.*
from tablea
inner join table b
on tableb.bookid = tablea.bookid
and tableb.category in (406, 678, 252);
Now, your queries can use this book_of_interest rather than books. Frankly, I would start with this first. Query optimization with the right indexes goes a long way. Millions of rows in multiple table are manageable.
Materialized view
create materialized view mv_books_of_interest
as
select tablea.*, tableb.*
from tablea
inner join table b
on tableb.bookid = tablea.bookid
and tableb.category in (406, 678, 252);
with no data;
Periodically, run a cron job (or the like) to refresh it:
refresh materialized view mv_books_of_interest;
Partitioning data
https://www.postgresql.org/docs/9.3/ddl-partitioning.html will get you started. If your team is on-board with table inheritance, great. Give it a shot and see how that works for your use case.
Trigger
Create a field is_interesting in tableA (or tableB, depending on how you want to access data). Create a trigger that checks for a certain criteria when data is inserted in dependencies and then turns the book's flag true/false. That will allow your queries to run faster but could slow down your inserts and updates.

combining data from multiple tables to excel

I am trying to get data from multiple tables into one dataset in excel. I am a beginner sql.
Each table has Patient Number as a unique identifier.
Table 1 may have 1 columns that result in 4 rows of data for any given patient.
Table 2 may have 7 columns that result in 26 rows of data for any given patient.
and so on. I pull data from 24 tables and it ends up being 61 columns and about 8000 rows. Problem is, if I try to join all of these tables with the Patient Number, I end up with 10's of thousands of rows returned.
Right now I am just running 24 separate queries, putting the results of each one in a separate tab on my spreadsheet and then running a macro to combine all the tabs into one spreadsheet with 61 columns.
Seems like sql should be able to do this. But I am a beginner so I am having trouble figuring it out.
Question was not exatcly clear, But what I understood is that you need a easy way to save thease data in "sql" to a spreadsheet. I recommend you to use CSV(Comma separated Vlaues) formatting .Because You can easily define the Column headers on your own and it easy to add data to each column and you can foget about the "Tab" thing which is a complex approach.
Use ArrayList to save all pataients Objects.Each and every object in that List will carry all the information for a particular patient ,which fetched from your SQL Database.
Refer this for more info in CSV
Hope this Helps!
Ok I got some help with this.
I ended up using a Union All. The problem with that before was that all my different tables had different numbers of columns and different numbers of rows for my key identifier. So I can use a Union All if I use Null in my select statements so that I have the same number of columns in all my select statements. Then the query just stacks all of the data together:
Many thanks to Kris at http://www.essentialsql.com/
I have 19 tables and 62 column, so I have a way to go before I finish the query.
(SELECT PatientID, 1 as TableOrder, A1, A2, NULL as B1, NULL as B2, NULL as C1, NULL as C2
FROM TableA
UNION ALL
SELECT PatientID, 2, NULL, NULL, B1, B2, NULL, NULL
FROM TableB
UNION ALL
SELECT PatientID, 3, NULL, NULL, NULL, NULL, C1, C2)
ORDER BY PatientID, TableOrder

Combining different tables in excel by looking up values

Okay, so let's say I have two tables in Excel. I want to create a third table that looks up data from the other two and combines them. I'll explain what I mean
Here is my first table:
It has a number, which is like a primary key, and a corresponding name for each entry.
I also have a second table:
This one just contains some random info, and there's numerous entries. The Client Name is not listed here, but it does have the key for the client that each entry corresponds to.
I want to create a third table that shows me all the Client Info data, but replaces the key with the actual client name. So basically, wherever it sees a key of "1", it'll look that up from the first table and find "Comet" instead.
The desired table would look like this:
What kind of formula would I need to pull data from one table based on a value? Note that all my tables are in different worksheets.
Assuming that the three tables are in Sheet1, Sheet2, Sheet3, this is the formula you need in Sheet3, cell A2
=vlookup(Sheet2!A2,Sheet1!$A2$b$6,2,false)
Copy down as many rows as there are rows in Sheet2
If you need the client info from Sheet2, use this in Sheet3, cell B2 and copy down
=sheet2!B2
As you put an "SQL" tag, I assume that you are also looking for an SQL based answer. So in addition to #teylyn suggestion, you can use the following SQL query if you are working with SQL databases:
SELECT table1.Client_Name, table2.Client_Info
FROM table1
RIGHT JOIN table2 ON table1.ID_Number = table2.ID_Number
Here is what this query does:
The RIGHT JOIN will return all rows from the right table (here table2), with the matching rows in the left table (here table1) according to the condition specified by the ON clause (here, if the ID Number is the same). Then, the SELECT clause will return a table with ONLY the columns specified after the keyword SELECT.

How can i update a table using this view

I have 3 tables called Airlines,Destinations and PriceTable.
The Airlines table has two columns - Airline_ICAO_Code and Airline. The Destinations table has two columns - Airport_ICAO_Code and Destination. The PriceTable has these columns - ID,Airport_ICAO_Code, Airline_ICAO_Code,Departure,Price and RouteStaus.
The PK in PriceTable is ID.The PK in Airlines table is Airline_ICAO_Code. The PK in Destinations table is Airport_ICAO_Code. The columns Airport_ICAO_Code and Airline_ICAO_Code in the price table are FKs.
I created a view called InputFlightPrices which i want to use to update the PriceTable which stores the flight prices. The reason im using the view to do this is that it allows me to see clearly what airline routes need updating as its difficult to determine the airline and destination from the codes.
This is the view code:
Create View InputFlightPrices
As
Select ID,Airline,Destination,AirportName,Price,Departure,RouteStatus
From Airlines As a
Join PriceTable As p
On a.Airline_ICAO_Code = p.Airline_ICAO_Code
Join Destinations As d
On d.Airport_ICAO_Code = p.Airport_ICAO_Code;
I want the view to display all airlines a-z but I cannot use an Order By clause in the view.
I therefore ran the query below on the view to order the airlines in the view A-Z
Select * from InputFlightPrices
Order By Airline Asc
The resulting view from the above statement displays correctly but it does not allow me to edit the records in it in order to update the table.
Is there a solution.
Thanks for any help offered.
Im editing this in response to Philpxy to try and clarify what i want:
I want to update a table called PriceTable which contains flight prices.
The Airline and Destination columns within the PriceTable contain codes. It is difficult to know what airline and destination to update from these codes so I created a view called InputFlightPrices which shows the Airline and Destination names. This makes it easy to enter the prices for the correct routes.
The problem with the View is that the Airline column is not sorted. Records belonging to an Airline are scattered throughout the table. This could lead to me missing some routes that need to be updated.
Therefore I created a select statement which Ordered the View by Airline A-Z.
The problem that i have now is that I cannot update the PriceTable using this View(the result of select statement) as It does not allow me to edit it.I tried to edit by clicking it directly using the GUI.
I hope thats clear.
As you have multiple joins in view, the update may not update the records correctly. You can use triggers here to update the table.
You may be able to edit your Select * from InputFlightPrices Order By Airline Asc query per answers to How to quickly edit values in table in SQL Server Management Studio?:
In Mgmt Studio, when you are editing the top 200, you can view the SQL
pane - either by right clicking in the grid and choosing Pane->SQL or
by the button in the upper left. This will allow you to write a custom
query to drill down to the row(s) you want to edit.
Go to Tools > Options. In the tree on the left, select SQL Server
Object Explorer. Set the option "Value for Edit Top Rows command" to
0. It'll now allow you to view and edit the entire table from the context menu.
Re updating when the query result involves a view:
From SQL Server 2014 CREATE VIEW (Transact-SQL)
The SELECT clauses in a view definition cannot include the following:
An ORDER BY clause, unless there is also a TOP clause in the select list of the SELECT statement
The ORDER BY clause is used only to determine the rows that are returned by the TOP or OFFSET clause in the view definition. The ORDER
BY clause does not guarantee ordered results when the view is queried,
unless ORDER BY is also specified in the query itself.
[...]
You can modify the data of an underlying base table through a view, as
long as the following conditions are true:
Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.
[...]
Generally, the
Database Engine must be able to unambiguously trace modifications from
the view definition to one base table.
Per the last sentence: If you want to update a base table for a particular row then it has to be just one base table's columns, columns of some key from that base table must be in the view (UNIQUE NOT NULL or PRIMARY KEY), and you must not be updating those columns.
Otherwise when you ask to update some row in the view it's not clear what row in what base table is to be updated.
See also SQL Server 2014 Modify Data Through a View.

select into a table with different column names

In SQL, Select into ... copies rows into a different (backup) table. Is this possible if the backup table has different structure (or different column names)? If not, what is the best way to achieve this?
Here is what I want to do: TableA has columns a1,a2,a3. I want to copy some rows from this table to another table TableB which has column b1,b2,b3,b4. Content of a1 to go into b1, a2 to b2 etc.
The column names do not matter at all, as long as data types match (or can be cast in the assignment).
If the data types of the columns don't match, try casting the values accordingly. Just try with small dummy tables. Be sure to list the target columns explicitly to avoid confusion. Like this:
INSERT INTO TableB (b1, b2, b3)
SELECT a1, a2, a3
FROM TableA
WHERE <some condition>;
More details in the SQLite manual here.