Creating tables - int in quotes? - sql-server-2008

When I create a table and I am putting an int, is this ok:
insert into Employee_T
(Emp_Id)
values
(
'100' /*WILL THERE BE A PROBLEM IF I PUT IT LIKE THIS, IE WITH THE QUOTES*/?
)

It is perfectly valid, but entirely unnecessary, to put an integer literal in quotes.
It will be parsed as a string and automatically converted to an integer.
See it working online: sqlfiddle

No problem: the string literal will be CAST to int on insertion.
I wouldn't normally do it myself because it is misleading though...

No,
this should work just fine.
The sql server will the parse the string and convert it into a integer.
Of course this is not optimal for performance,
and it also can cause problems if some formatting like 1.000 or 12,000 is in the string...

No, it's not a problem. I mean, it won't cause an error. Maybe there is just a little performance overhead of converting the types. It's little but unnecessary and may show up on high load.

Quotes are used in case the type is char or varchar. If you are using int then there is no need to give quotes for inserting the values. You should use the following query:-
insert into Employee_T (Emp_Id) values (100);
However, the SQLServer support quotes also for int. But its a good practice if you are not using quotes for int.

Related

Join returns NULL when data that matches is in the table

I'm trying to get results when both tables have the same machine number and there are entries that have the same number in both tables.
Here is what I've tried:
SELECT fehler.*,
'maschine.Maschinen-Typ',
maschine.Auftragsnummer,
maschine.Kunde,
maschine.Liefertermin_Soll
FROM fehler
JOIN maschine
ON ltrim(rtrim('maschine.Maschinen-Nr')) = ltrim(rtrim(fehler.Maschinen_Nr))
The field I'm joining on is a varchar in both cases. I tried without trims but still returns empty
I'm using MariaDB (if that's important).
ON ltrim(rtrim('maschine.Maschinen-Nr')) = ltrim(rtrim(fehler.Maschinen_Nr)) seems wrong...
Is fehler.Maschinen_Nr really the string 'maschine.Maschinen-Nr'?
SELECT fehler.*, `maschine.Maschinen-Typ`, maschine.Auftragsnummer, maschine.Kunde, maschine.Liefertermin_Soll
FROM fehler
JOIN maschine
ON ltrim(rtrim(`maschine.Maschinen-Nr`)) = ltrim(rtrim(`fehler.Maschinen_Nr`))
Last line compared a string to a number. This should be doing it.
Also, use the backtick to reference the column names.
The single quotes are string delimiters. You are comparing fehler.Maschinen_Nr with the string 'maschine.Maschinen-Nr'. In standard SQL you would use double quotes for names (and I think MariaDB allows this, too, certain settings provided). In MariaDB the commonly used name qualifier is the backtick:
SELECT fehler.*,
`maschine.Maschinen-Typ`,
maschine.Auftragsnummer,
maschine.Kunde,
maschine.Liefertermin_Soll
FROM fehler
JOIN maschine
ON trim(`maschine.Maschinen-Nr`) = trim(fehler.Maschinen_Nr)
(It would be better of course not to use names with a minus sign or other characters that force you to use name delimiters in the first place.)
As you see, you can use TRIM instead of LTRIM and RTRIM. It would be better, though, not to allow space at the beginning or end when inserting data. Then you wouldn't have to remove them in every query.
Moreover, it seems Maschinen_Nr should be primary key for the table maschine and naturally a foreign key then in table fehler. That would make sure fehler doesn't contain any Maschinen_Nr that not exists exactly so in maschine.
To avoid this problems in future, the convention for DB's is snake case(lowercase_lowercase).
Besides that, posting your DB schema would be really helpfull since i dont guess your data structures.
(For friendly development, is usefull that variables, tables and columns should be written in english)
So with this, what is the error that you get, because if table "maschine" has a column named "Maschinen-Nr" and table "fehler" has a column named "Maschinen_Nr" and the fields match each other, it should be correct
be careful with Maschinen-Nr and Maschinen_Nr. they have - and _ on purpose?
a very blind solution because you dont really tell what is your problem or even your schema is:
SELECT table1Alias.*, table2Alias.column_name, table2Alias.column_name
FROM table1 [table1Alias]
JOIN table2 [table2Alias]
ON ltrim(rtrim(table1Alias.matching_column)) = ltrim(rtrim(table2Alias.matching_column))
where matching_columns are respectively PK and FK or if the data matches both columns [] are optional and if not given, will be consider table_name

Are numbers seen as strings in sql

This is really simple. Does SQL SERVER 2008 auto convert values to string for you ?
I tried this Select * from Staff Where Division = 5
If I try to insert it, it works too.
If I change 5 for five I get and error though. Invalid column name five.
Division is a NVARCHAR. Shoudn't the 5 be within single quotes ?
Yes, SQL Server does an implicit conversion of int to nvarchar. It can also implicitly convert nvarchar to int (and other numeric types).
For more details: http://msdn.microsoft.com/en-us/library/ms191530.aspx
There are a lot of cases where implicit conversion takes place. For example:
EXEC sp_who2 active;
Shouldn't you need to delimit active as a string? Yes, but the syntax is forgiving.
My suggestion: always delimit data types correctly, and ignore the exceptions. The chances they'll ever get comprehensively fixed are close to nil.

Single Quotes in MySQL queries

If I have a MySQL query like:
SELECT this FROM that WHERE id='10'
and
SELECT this FROM that WHERE id=10
both seem to work correctly.
What is the use of the single speech marks in MySQL queries? When is it correct to use them?
When MySQL performs the query, there is an implicit conversion of the argument.
If id is INT, then '10' is cast to an integer.
If id is VARCHAR or another text type, 10 is cast to string.
In both cases both queries will work (unless you are running in STRICT mode).
From a performance point of view, you have to use the right data type (do not use quotes for integer arguments) - the implicit cast adds overhead and in some cases, it may hurt the performance of index lookups.
From security perspective, it easier to always use quotes and mysql_real_escape_string (in case the argument is not quoted, mysql_real_escape_string won't stop any attack, that do not use quotes, for example 'UNION SELECT password FROM users'. However, better approach is to cast your variable to int, when it's expected to be int, or use prepared statements
If the value is a string, you have to use ' or ".
If the value is a number, like in your example, you have not to use ', but MySQL handles it if you put it around 's.
Assuming that id is a numeric column, what happens is that MySQL casts your parameter to number automatically so data types match before comparing. It works flawlessly unless casting provides unexpected results. E.g., these expressions with match the row with id=10 because all the strings cast to 10:
id='10'
id=' 10'
id='00010'
id='10foo'
The following will not match the row because non-parseable strings cast to 0 and 10<>0:
id='foo10'
id='bar'
When to use each? If you want a string, you need to quote it (there's no other way to type a string and get valid SQL). If you want a number, it must be unquoted (otherwise, you'll get a string that happens to contain a number). Of course, you can always provide numbers as strings and let MySQL do the conversion, but it doesn't really add anything to the query apart from one extra step and possibly incorrect results that go unnoticed.
You should always use them. They can help to stop SQL injection attacks because mysql_real_escape_string isn't enough on its own.
That is assuming you are running a query via PHP.

MySQL Single Quote Efficiency

I live in Australia, so postcodes are numeric and four digits long.
In a table steup by another person the postcode field has been setup as a VARCHAR(10) - strange i know!!!
There is a difference between the following two query times:
Postcode='3000'
Postcode=3000
Both queries run, but the one with single quotes around it runs between 50% to 80% faster. Likewise postcode IN('3000','3001','3002') is much faster than Postcode IN(3000,3001,3002). The postcode field is indexed
The quesiton is HOW do the single quotes make so much speed difference?
Can anyone shed any light on how the engine optimizes the above queries?
There is one important trap in this.
If you use something like
code = 1000
instead of
code = '1000'
then if you had other dataset, the first case would return all records like:
'1000', '1000A', '1000B'
etc, while the second would return as expected only '1000'. This might be the reason of performance issue. Some mentioned that it converts int to varchar. I believe it converts all varchars to int and that is why it is noticable
When you don't include the quotes, the interpreter has to take the time to do an implicit conversion from int to varchar. If you use quotes, it's already a varchar and it saves the time of doing a conversion to the native storage format.

MySQL Tri-state field

I need to create a good/neutral/bad field. which one would be the more understandable/correct way.
A binary field with null (1=good, null=neutral, 0=bad)
An int (1=good, 2=neutral, 3=bad)
An enum (good, neutral, bad)
Any other
It's only and informative field and I will not need to search by this.
NULL values should be reserved for either:
unknown values; or
not-applicable values;
neither of which is the case here.
I would simply store a CHAR value myself, one of the set {'G','N','B'}. That's probably the easiest solution and takes up little space while still providing mnemonic value (easily converting 'G' to 'Good' for example).
If you're less concerned about space, then you could even store them as varchar(7) or equivalent and store the actual values {'Good','Neutral','Bad'} so that no translation at all would be needed in your select statements (assuming those are the actual values you will be printing).
In Mysql you ought to be using an enum type. You can pick any names you like without worrying about space, because Mysql stores the data as a short integer. See 10.4.4. The ENUM Type in the documentation.