Create hidden column in postgresql - database

Can we create hidden column in the table. It should be listed only when I specify column name explicitly in select statement.

No, there is no supported and safe way to create a hidden column that's listed only when you specify the column name explicitly. PostgreSQL doesn't provide any user-accessible way to hide user-defined columns from the * wildcard.
You could use any user interface layer / query builder of your choice to do this, though.
(PostgreSQL actually does have hidden columns, as you'll see if you select ctid,xmin,xmax from some_table, but it doesn't allow users to add to the set of hidden columns. It is possible to modify the system catalogs directly to trick PostgreSQl into thinking that a user defined column is a hidden system column, but it's a really bad idea to mess directly with the catalogs, so I won't explain how in detail. If you insist on doing this, read the documentation on pg_attribute ... but understand that you're creating a giant foot gun.).
You can set column permissions so a user can only select some columns, though again you can't say "all except this one", you have to say "I want them to be able to see these ones".
Update: #maybeWeCouldStealAVan has the most sensible suggestion: you probably want a view. Mark that answer as correct, not mine.

You can effectively do this by creating a view and selecting only the columns you wish to show.

Related

Rename table or column in SQL server without breaking existing apps

I have an existing database in MS SQL server and want to rename some tables and columns because the names currently used aren't accurate to what it represents.
I have multiple web and desktop applications that access the database, using Entity Framework (code first). Too many to update in one go and cannot afford for all apps to start working.
I was thinking it was nice is SQL server allowed a 'permanent' alias for tables and columns but I don't think this feature exists.
Or I was wondering if there was a way in EF to have two names for the same property?
For the tables, you could rename them and then create a synonym with the old name pointing to the new name.
For the columns, changing their name will break your application.You could create computed columns with the old name as well, that simply display the value of the new named column though (but this seems a little silly).
Note, however, that a computed column cannot reference another computed column, so you would have to duplicate the column in its entirety. That could lead to problems down the line if you don't update the definition of both columns.
A view containing a simple select statement acts exactly like a table. You really need to fix this properly across the database and applications. However if you want to go the view route, I suggest you do this:
Say you have a table called MyTable that you rename TheTable and with a column called MyColumn that you want to rename to TheColumn
Create a schema, say, new
Move the original table into it with this ALTER SCHEMA new TRANSFER MyTable
Rename the table and column.
Now you have a table called new.TheTable with a column called TheColumn. Everything is broken
Lastly, create a view that looks just like the old table
CREATE VIEW dbo.MyTable
AS
SELECT Column1, Column2, Column3, TheColumn As MyColumn
FROM new.TheTable;
Now everything works again.
All your fixed 'new' tables are in the new schema
However now everything is extra complicated
This is basically an illustration that you should just fix it properly across the whole app one at a time with careful change management. Definitely don't complicate it with triggers
Since you are using code first with multiple web and desktop applications, you are likely managing database changes from one place through migrations and ignoring changes other places.
You can create an empty migration and add code that will change the table name and column names to what you want. The migration should then create a view that will select from that table with the original table and column names. When you apply this migration, everything should still be working as normal from all applications. There are no model changes since you didn’t touch the model classes. Inserts, updates, and deletes will still happen through the view. There is no need for potentially buggy triggers or synonyms on the table in this option.
Now that you have the table changed, you can focus on the application code. If it helps, you can add annotations over the column and table names and start refactoring the code. You need to make sure you don’t make model changes that will break the other apps. If apps ignore model changes, you can get away with adding annotations over the columns and classes on all the apps before refactoring. You can get rid of the view sooner this way.

How to ensure column name does not match with any SQL Server reserved word

I'm using a query command to create a SQL Server table. I don't want the column name do match any of the SQL Server keywords (ex: use, create,...). How to check the column names (in query string) do not match any SQL Server keywords?
Update 1:
Of course, except for creating a keyword list, then go hand-in-hand comparison.
Since you're asking about naming, let me give you a piece of advice which will lead to one possible answer to your question:
If you're not sure, just get into the habit of always surrounding object names in [SquareBraces], then it doesn't matter too much what you call your objects.
But having said that, it's definitely best to follow a good convention, either the convention common in your workplace, or find another sensible convention to follow (sometimes it seems there are more opinions about naming conventions than there are people coding them!).
My preferences (FWIW) put simply are:
Table names that reflect the entity that a single row contains, eg, [Order], [OrderLine], [Customer], etc. To answer your original question, you'll notice that ORDER is a keyword here, but as soon as you put square braces around it the parser knows it's an object. Works every time, and you don't have to make contrived or redundant names for the table that holds Order records, for example CustomerOrder.
Composite table names for many-many linking tables reflect both tables being linked where it makes sense, such as [Customer_Contact], [Product_ProductCategory], etc.
Primary keys are always called simply [Id], regardless which entity it is a primary key for, unless there's a very good technical reason not to, which is rare.
Foreign keys are named after the table and column of the PK they refer to, eg. [CustomerId].
As to why I name tables in the singular, rather than think of a table as a collection of, say "Customers", I think of it as a repository where objects of the type "Customer" are stored. This works particularly well when using some ORMs (I like Dapper in C#, but it doesn't work so well with some others where pluralism is almost forced), so you'll have to work out what works best for you and what you're most comfortable with.
Good luck!
While writing the script to create a table, a column name that matches a keyword will change in color either pink, blue, grey. Just encase the column in question with [].
Example:
CREATE TABLE MyTable([DateTime] datetime)
Not sure if there's a system table in system databases where you could query this from but dropping it here it case it may be of use to you.
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql?view=sql-server-2017

MS Access 07 - Q re lookup column vs many-to-many; Q re checkboxes in many-to-many forms

I'm creating a database with Access. This is just a test database, similar to my requirements, so I can get my skills up before creating one for work. I've created a database for a fictional school as this is a good playground and rich data (many students have many subjects have many teachers, etc).
Question 1
What is the difference, if any, between using a Lookup column and a many-to-many associate table?
Example: I have Tables 'Teacher' and 'Subject'. Many teachers have many subjects. I can, and have, created a table 'Teacher_Subject' and run queries with this.
I have then created a lookup column in teachers table with data from subjects. The lookup column seems to take the place of the teacher_subject table. (though the data on relationships is obviously duplicated between lookup table and teacher_subject and may vary). Which one is the 'better' option? Is there a snag with using lookup tables?
(I realize that this is a very 'general' question. Links to other resources and answers saying 'that depends...' are appreciated)
Question 2
What attracts me to lookup tables is the following: When creating a form for entering subjects for teachers, with lookup I can simply create checkboxes and click a subject for a teacher 'on' or 'off'. Each click on/off creates/removes a record in the lookup column (which replaces teacher_subject).
If I use a form from a query from teacher subject with teacher as main form and subject as subform I run into this problem: In the subform I can either select each subject that teacher has in a bombo box, i.e. click, scroll down, select, go to next row, click, scroll down, etc. (takes too long) OR I can create a list box listing all available subjects in each row but allowing me to select only one. (takes up too much space). Is it possible to have a click on/off list box for teacher_subject, creating/removing a record there with each click?
Note - I know zero SQL or VB. If the correct answer is "you need to know SQL for this" then that's cool. I just need to know.
Thanks!
Lookup columns in tables will cause you more stress than joy. Unless you need them for Sharepoint, they should be avoided. You may wish to read http://r937.com/relational.html and http://www.mvps.org/access/tencommandments.htm
I wouldn't use them. Your example is fine, but there are limitations. What do you do when you need to reference another field from the Subject table other than the name? How would you differentiate subjects that are only offered on a semester basis?
You have no way of getting a count of how many subjects each teacher is assigned without some ugly coding.
Another limitation, is when you start identifying who taught what courses during a given school year.
I'm kind of unclear on your second question, but it sounds to me like you need a subform with a dropdown list.
If you want to do the checkbox thing, it quickly becomes a lot more complicated. To me, you're starting from user interface and working backwards to structure, instead of going the other direction.
I hesitate to mention it, but in terms of full disclosure you should know that in A2007 and A2010, you have multi-value fields available, and they are presented with exactly the UI you describe. But they have many of the same problems as lookup fields, and are quite complex to work with in code. Behind the scenes, they are implemented with a standard many-to-many join table, but it's all hidden from you.
I wish MS would make the listbox with checkbox control that is used with MV fields available for all listboxes, but binding that to a many-to-many join table would be complex if the listbox control were not designed for that (with link child/link master properties, for instance).
I tried to come up with a way to offer you the UI feature you prefer from multi-value fields without actually using multi-value fields. That seems challenging to me.
The closest I could come up with is to load a disconnected recordset with your "List" choices and a check box field. Then create a form, or subform, based on that recordset which you present in datasheet view. It could look similar to a combo bound to a multi-value field. In the after update event of the checkbox field, you would need code to add or remove a record from the junction table as required.
However, I don't know if this is something you would care to tackle. Earlier you indicated a willingness to learn SQL if needed; the approach I'm suggesting would also require VBA. Maybe take a look at Danny Lesandrini's article, Create In-Memory ADO Recordsets, to see whether it is something you could use.
OTOH, maybe the most appropriate answer for you is to keep the multi-value fields and get on with the rest of your life. I'm stuck. But now that we know you are actually using multi-value fields, perhaps someone else will be able to offer you a more appropriate suggestion.

Database design - do I need one of two database fields for this?

I am putting together a schema for a database. The goal of the database is to track applications in our department. I have a repeated problem that I am trying to solve.
For example, I have an "Applications" table. I want to keep track if any application uses a database or a bug tracking system so right now I have fields in the Applications table called
Table: Applications
UsesDatabase (bit)
Database_ID (int)
UsesBugTracking (bit)
BugTracking_ID (int)
Table: Databases:
id
name
Table: BugTracking:
id
name
Should I consolidate the "uses" column with the respective ID columns so there is only one bug tracking column and only one database column in the applications table?
Any best practice here for database design?
NOTE: I would like to run reports like "Percent of Application that use bug tracking" (although I guess either approach could generate this data.)
You could remove the "uses" fields and make the id columns nullable, and let a null value mean that it doesn't use the feature. This is a common way of representing a missing value.
Edit:
To answer your note, you can easily get that statistics like this:
select
count(*) as TotalApplications,
count(Database_ID) as UsesDatabase,
count(BugTracking_ID) as UsesBugTracking
from
Applications
Why not get rid of the two Use fields and simply let a NULL value in the _ID fields indicate that the record does not use that application (bug tracking or database)
Either solution works. However, if you think you may want to occasionally just get a list of applications which do / do not have databases / bugtracking consider that having the flag fields reduces the query by one (or two) joins.
Having the bit fields is slightly denormalized, as you have to keep two fields in sync to keep one piece of data updated, but I tend to prefer them for cases like this for the reason I gave in the prior paragraph.
Another option would be to have the field nullable, and put null in it for those entries which do not have DBs / etc, but then you run into problems with foreign key constraints.
I don't think there is any one supreme right way, just consider the tradeoffs and go with what makes sense for your application.
I would use 3 tables for the objects: Application, Database, and BugTracking. Then I would use 2 join tables to do 1-to-many joins: ApplicationDatabases, and ApplicationBugTracking.
The 2 join tables would have both an application_id and the id of the other table. If an application used a single database, it would have a single ApplicationDatabases record joining them together. Using this setup, an application could have 0 database (no records for this app in the ApplicationDatabases table), or many databases (multiple records for this app in the ApplicationDatabases table).
"Should i consolidate the "uses" column"
If I look at your problem statement, then there either is no "uses" column at all, or there are two. In either case, it is wrong of you to speak of "THE" uses column.
May I politely suggest that you learn to be PRECISE when asking questions ?
Yes using null in the foreign key fields should be fine - it seems superfluous to have the bit fields.
Another way of doing it (though it might be considered evil by database people ^^) is to default them to 0 and add in an ID 0 data row in both bugtrack and database tables with a name of "None"... when you do the reports, you'll have to do some more work unless you present the "None" values as they are as well with a neat percentage...
To answer the edited question-
Yes, the fields should be combined, with NULL meaning that the application doesn't have a database (or bug tracker).

How to change a column's "Row Source" in Access table at run-time?

I would like to change the "Row Source" values in an Access table through code.
This way I can filter what a user can choose in a column's combo box.
In line with Dave DuPlantis' answer, you may wish to read "The Evils of Lookup Fields in Tables" From the Access Web by various Microsoft Access MVPs.
I don't know whether or not this is an option for you, but I would recommend separating the table and filtering options, setting up a form to do the data entry and modification and using code to set the Row Source for the combo box on the form. As you've already seen, while Access does provide the opportunity to treat tables as more than just tables, that is primarily for GUI purposes. Behind the scenes, Access prefers that you work with forms for data entry.
If you need to pursue the table method, you might try looking at the MS knowledge base articles referenced here. (The kb articles are here and here.) Keep in mind that these refer to Access 97 and may no longer be relevant. I wasn't able to find any more recent references to those properties in an Access tabledef.
Your question is quite confusing. "RowSource" is a property of a list box or combo box. A table does not have a RowSource, but, as Remou points out, Access allows you to define fields in your tables so that they display a combo box that looks up values from a related table. This combo box has a rowsource, so it's perhaps what you mean, but it's simply a terrible idea.
That combo box that you define in the table design is a user interface object, and UI doesn't belong in your table definitions. Not only does it lead to all sorts of problems, but it means your tables themselves can be broken by changes to other tables that invalidate the definition of the lookup fields.
User interface controls belong in user interface objects, which means that you should be putting them only in forms (or, at the lowest level, in saved queries).
Filtering for a user is, again, a user interface issue, and not one that has anything to do with table design.

Resources