I was wondering if it ok to use a question as a field name or column on a table such as IsTheWetherNiceOutsite? is there any pros or cons, or is there any other way to archive this?
If I were you I'd avoid column names with special characters like ? in the table itself. Writing queries can get troublesome.
But you can use column aliases if you want. For example,
SELECT NOW() 'What time is it?',
t.weatherNice 'Is the weather nice?'
FROM table t
It's not necessary. The is prefix already indicating that it's a boolean flag.
Prefer not to use weird characters, it might work (if use use backticks for the column name), but might not be portable, and will certainly confuse others.
Related
I have a column that has brand names in an array format as below:
I want to extract information associated with Brand4 for example 'price'.
I tried using the below, but that's a psql query. How can I extract this information using MySQL in GCP.
SELECT Brand_name, price
FROM table_name
Where 'Brand4'=Any(Brand_name)
First, the explanation for your error message is that in MySQL, ANY() accepts a subquery, not just a single column or expression. See https://dev.mysql.com/doc/refman/8.0/en/any-in-some-subqueries.html
MySQL does not have an array type. Your Brand_name column is not an array, it's a string. It happens to contain commas and square brackets, but these are just characters in a string.
So your solutions are to use various string-search functions or expressions, as other folks have suggested.
The downside to all the string-search functions is that they cannot be optimized with a conventional index. So every search will be expensive, because it requires a table-scan.
Another solution I did not see yet is to use a fulltext index.
alter table brands add fulltext index (brand_name);
select * from brands
where match(brand_name) against ('Brand4' in boolean mode);
This may require some special handling if the brand names contain spaces or punctuation, but if they are plain words, it should work.
Read https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html to understand more about fulltext indexes.
The best solution would be to eliminate this fake "array" column by normalizing the schema to store one brand per row in another table. Then you can match strings exactly and optimize with a conventional index. But I understand you said that the table structure is not up to you.
This should work in MySQL (using a string function as mention here):
SELECT *
FROM brands
WHERE FIND_IN_SET('Brand4',brand_name);
see: DBFIDDLE
Provided SQL query will work in MySQL, if you will make a subquery within the parentheses, or use FIND_IN_SET instead of using ANY.
But, as stated in the MySQL documentation:
This function does not work properly if the first argument contains a
comma (,) character.
So, as an alternative, you could use LIKE (simple pattern matching).
Your SQL code then would be:
SELECT `brand_name`, `price`
FROM `test`
WHERE `brand_name` LIKE "%Brand4%"
See SQLFiddle for live example.
Also, you could use LOCATE.
Or any other alternative solution.
But, I must say that storing list data in the way you do, - it's not the best practice out there.
There are plenty of ways this can be done better.
For example, using M:M (many-to-many) relationship.
In case you made this design you really have to reconsider/redesign. Databases have there own data structures and sql is not an imparative language but a declaritve one.
If when you didn´t desing you should consider create a table out of the one column. Perhaps this is what you try.
If it is just locating a specific string in the values of a field use like
SELECT Brand_name, price
FROM table_name
Where brand_anme like '%Brand4%'
But realize this is will not always yield accurate results.
May be this question has been answered before but I couldn't find it.
I am using a 2/3 yr old MySQL database which has hyphens in its column names. When I try to use these names from my Java code, the names are broken at the hyphen (e.g. air_port becomes air) and thus are not found. I tried replacing hyphens to underscores in my code hoping that the DB might treat them equally but that doesn't work.
How can I escape the hyphen or how can I access these columns ? Could this be an issue of the character set being used ?
enclose the names within `back-ticks`
Do you have hyphens (-) or underscores (_) in your column names?
Hyphens are a big problem because if you end up mapping a column name to a variable, most languages do not like to have hyphens inside variable names. Perhaps you are using one of the Java libraries that automatically generates variables or objects whose names are based on column names.
Depending on the nature of your problem, there are a couple of different approaches you can use:
Rename all of your columns using ALTER TABLE. Be conscious that this could affect referential integrity or other applications that depend on the database. If you don't know what that means, don't do it.
Create SQL views that simple restate the tables you need but with "better" column names. This is not very efficient, but it will allow you to get what you want.
Use the AS keyword when running your SELECT statements to rename columns within queries.
None of these are great solutions, but they should get you started. Good luck!
It's better to not use hyphens in your column names. I suffered a big problem with JOIN statements where hyphens caused big trouble - there even escaping names in back ticks didn't work.
Convert the column names to use underscores - this is the safest way to go.
As an alternative - in case where even backticks should cause problems (you know it happend to me) and you want to stick to hypens no matter what - just create a VIEW to reflect the same table with all the fields and query the view instead of the original table.
Hyphens in database names aren't good also. But you can use them with the backtick trick `
`name-with-hyphen`
This entry at the MySQL forum suggests that you might have a problem. However, I think it's referring to data and not column names.
This says "don't do it." Don't know how authoritative it is.
I had to create a db named pre-ca_db.
I solved the problem with
create database `pre-ca_db`;
Good luck!
One common issue I run into when naming columns in a new database table is the right name to use for classifying subtypes. The most natural column name is typically type, but I try to avoid using SQL keywords or reserved words in my naming.
I'm aware that type is a non-reserved keyword in both MySQL and Postgres, so I can use it, but should I?
What is current best practice around using type as a column name? Is there a synonym which is so broadly equivalent that it just makes sense to use that?
Over the years I've spent way to much time trying to pick other names and this has come up twice in discussions in the past week, so I wanted to see if there is any clear consensus around this?
In case it helps anyone else, some alternatives I've used in the past to try to get around this include:
category
kind
subtype
type_of
role
class
<entity>_type
my suggestion is usually to avoid using keywords but not because they're reserved but because they're often actually ambiguous in and of themselves.
For example, say you have a customer table - with a column 'type' this might be filled with segmentation (high value/low value etc) or it could be filled with source (direct marketing/walk in etc).
"Type" is a low-value word. I'd usually recommend being as explicit as possible at the expense of column-length. For example 'CustomerSourceType' or 'InventoryLocationType' or whatever is actually clearer in the scenario.
Trailing underscore
The SQL standard explicitly promises to never use a tailing underscore on any keyword, reserved word, etc.
So if you name your identifiers (table names, column names, index names, etc.) with a trailing underscore, you need never worry about a collision.
CREATE TABLE product_ (
name_ VARCHAR ,
type_ VARCHAR ,
…
);
The advice others gave to “avoid using reserved words” is naïve, is likely to fail, and is not portable. Many years ago I did a quick survey of various database products and their keywords. I collected a distinct list of about a thousand. Really. You would not believe how many non-obvious words are used in various ways by various products. Of course, collisions are context-dependent, so not all reserved words will be a problem if used by you in particular ways. But the trailing underscore trick relieves you of the need to study each product’s list of reserved words and monitor your codebase for potential collisions.
Naming is tricky. Of course you should make an effort to use the most clearly descriptive name possible. Sometimes, especially in a particular problem domain, a word like “type” might be appropriate. If so, add the trailing underscore (type_) and sleep well.
First rule,
Never ever ever ever use Keywords or Reserver words. The person coming after you will suffer.
If you are only using 'Type' for this time. You could use Types
Naming a column "type" is technically fine it seems. I name my columns to avoid confusion with methods / keywords in the language / frameworks I might use to query to database.
Also, what if I add a new language or framework that interfaces with the DB.
"type" is a method name or keyword in many languages.
Perhaps for no good reason (it does take away some awesome column names). Shouldn't be that big a deal either way. Just a personal preference.
This question already has answers here:
MySQL query finding values in a comma separated string
(11 answers)
Closed 5 years ago.
I have a MySQL field with a reference to another table where ids are saved as comma seperated list, eg:
12,13,14,16
which stand for values in another table. I know this is very bad and wrong, but this comes from above and I cant do anything about that. The problem now is that i want to search in that field with a query like this:
SELECT ... WHERE field LIKE '%1%'
The Problem now is obviously that almost all entries can be found with this example Query, because the most common IDs are in Range 10-20. My Idea is to search for %,1,% instead, but this does not work for the first and last id in the field. Ist there something like an internal replace or how do i fix this the best way?
You need the FIND_IN_SET function:
SELECT ... WHERE FIND_IN_SET('1', field)
Be aware that plain FIND_IN_SET is case-insensitive,
i.e. FIND_IN_SET('b3','a1,a2,B3,b3') and FIND_IN_SET('B3','a1,a2,B3,b3') both return 3.
To be case sensitive, add 'binary' modifier to the 1st argument, e.g. FIND_IN_SET (binary 'b3', 'a1,a2,B3,b3') returns 4.
As others have said, Find_In_Set will let you write the query, but you really need to look at your database design (and I know you know this...)
The trouble with including Foreign Keys in a delimited list like this is that whole point of a foreign key is to enable you to locate the information in the other table quickly, using Indexes. By implementing a database as it sounds you have, you have all sorts of issues to resolve:
How do I prevent duplicates (which would waste space)
How do I remove a given value (Requires custom function, leading to possibility of errors?
How do I respond to performance issues as the size of my tables increase?
There's only one truly acceptable way to address this - which is not to face the problem in the first place.
Have a sit down chat with those on high, and explain the problems with their solution - then explain the advantages of doing the job properly.
If they won't even discuss the point, look for a job with a decent employer who values your contributions.
Martin.
FIND_IN_SET is your best bet
SELECT ... WHERE FIND_IN_SET(1,field_name)
After reading this question Id like to add that if your comma delimited list has spaces i.e. (1, 2,3 ,4) you will need to remove the leading/trailing spaces or use WHERE FIND_IN_SET(X,field) OR FIND_IN_SET(' X',field) OR FIND_IN_SET('X ',field)..... Just thought i'd share that since i came across that problem..... just gotta create those databases right the first time or they will give you all kinds of trouble.
May be this question has been answered before but I couldn't find it.
I am using a 2/3 yr old MySQL database which has hyphens in its column names. When I try to use these names from my Java code, the names are broken at the hyphen (e.g. air_port becomes air) and thus are not found. I tried replacing hyphens to underscores in my code hoping that the DB might treat them equally but that doesn't work.
How can I escape the hyphen or how can I access these columns ? Could this be an issue of the character set being used ?
enclose the names within `back-ticks`
Do you have hyphens (-) or underscores (_) in your column names?
Hyphens are a big problem because if you end up mapping a column name to a variable, most languages do not like to have hyphens inside variable names. Perhaps you are using one of the Java libraries that automatically generates variables or objects whose names are based on column names.
Depending on the nature of your problem, there are a couple of different approaches you can use:
Rename all of your columns using ALTER TABLE. Be conscious that this could affect referential integrity or other applications that depend on the database. If you don't know what that means, don't do it.
Create SQL views that simple restate the tables you need but with "better" column names. This is not very efficient, but it will allow you to get what you want.
Use the AS keyword when running your SELECT statements to rename columns within queries.
None of these are great solutions, but they should get you started. Good luck!
It's better to not use hyphens in your column names. I suffered a big problem with JOIN statements where hyphens caused big trouble - there even escaping names in back ticks didn't work.
Convert the column names to use underscores - this is the safest way to go.
As an alternative - in case where even backticks should cause problems (you know it happend to me) and you want to stick to hypens no matter what - just create a VIEW to reflect the same table with all the fields and query the view instead of the original table.
Hyphens in database names aren't good also. But you can use them with the backtick trick `
`name-with-hyphen`
This entry at the MySQL forum suggests that you might have a problem. However, I think it's referring to data and not column names.
This says "don't do it." Don't know how authoritative it is.
I had to create a db named pre-ca_db.
I solved the problem with
create database `pre-ca_db`;
Good luck!