Advice needed for VIEWS with some core columns and extra fields
0
votes
0
answers
35
views
I am looking for advice about designing VIEWs when a variable number of columns is needed.
Context
---
The tables are consolidated into views. For instance
office_rents
and office_electricity_bills
are consolidated into the view office_expenses
.
Views are themselves consolidated to an upper level by other views, e.g. office_expenses
, salaries
, a.s.o are consolidated into professional_expenses
.
From table columns id, date, amount, description, payment_method
the current VIEWs retain only the date
and amount
fields, which suffice to plot data.
However, having additional fields in views (description
, payment_method
) would be useful in some context, like listing the last paid invoices or the next ones to be paid.
---
Approaches considered
--
**I hesitate between the following approaches**:
**A)** The VIEWs contain all the fields required for all the needs ; this is close to a SELECT *
approach:
CREATE VIEW myView AS
SELECT date, amount, description, payment_method FROM table1
UNION ALL
SELECT date, amount, description, payment_method FROM table2
Pros: Simplicity
Cons: Performance due to bloated data, especially for some plots that ranges over years.
---
**B)** The VIEWS are duplicated, with more or less fields to serve the different purposes:
CREATE VIEW myViewLt AS
SELECT date, amount FROM table1
UNION ALL
SELECT date, amount FROM table2
CREATE VIEW myView AS
SELECT date, amount, description, payment_method FROM table1
UNION ALL
SELECT date, amount, description, payment_method FROM table2
Pros: Performance.
Cons: Twice more views to create and complicates maintenance.
---
**C)** The VIEWs contains only the columns that are always required, and an id
that points back to the table records to get the extra fields when needed.
CREATE VIEW myView AS
SELECT 'table1' AS source_table, id AS tid, date, amount FROM table1
UNION ALL
SELECT 'table2' AS source_table, id AS tid, date, amount FROM table2
Pros:
- Performance when only the minimal date
, amount
columns are
required.
- Flexibility for different purposes requiring variable number of columns.
- Creates a link to the original data, that can later be used
to manipulate them.
Cons:
- Will complexify code, requiring JOIN queries when the extra columns will be needed.
- Loss of performance if the extra columns are required for many records.
---
**Edit:** I went with approach **C** for pratical reasons.
---
N.B. I am using MariaDB (MySQL) or SQLite depending on the configuration.
Asked by OuzoPower
(141 rep)
Feb 26, 2025, 07:36 PM
Last activity: Mar 1, 2025, 07:55 PM
Last activity: Mar 1, 2025, 07:55 PM