I'm struggling to get a SQL statement to run.
I need to have an and / or statement which gives me:
Where Condition 1 is true
OR
Where both Condition 2 AND Condition 3 are true. (not only one of them)
Appreciate some ideas :)
You can split them with parenthesis, you also only need to define 'WHERE' once. Example:
WHERE
{condition_1} or ({condition_2} and {condition_3})
Edit: You don't technically require parenthesis due to AND having a higher precedence than OR, but it makes it much easier to read and see at a glance exactly what you're trying to do.
Related
So this is my third question in so many hours. Thanks again to everyone who has taken the time to help me through my SQL ordeal. I think this might be my last tango for the night, so here goes:
After taking some very good advice from #Vojtěch Dohnal, I converted one of my queries from a concatenated string to a parameterized SQL query here:
PARAMETERS NewPrefix TEXT; SELECT MAX([Suffix]) FROM [SalesTable] WHERE [Prefix] = [NewPrefix];
From what I can tell, this should be the right syntax for creating a parameterized query; the user will define what should go into the NewPrefix field and it will find the appropriate max function based on that. However, whenever I go to execute this query it hits me with the same 'Run-time error '5'; Invalid procedure call' error I've been wrestling with for about 9 hours now haha
I went ahead and tried to test the same query in the Access SQL query window, and I receive an error message there claiming: "This expression is typed incorrectly, or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables".
I'm not sure how to get around this. I don't think the syntax is wrong, but I can't find anything to compare it to on the Internet. I've used the debugger to step through and it looks like all of the values and variables and fields are populated correctly, but when it gets to the execute command it crashes with the same singularly unhelpful error message.
Thanks again for anyone who can help.
So it looks like the main problem that I was running into was that the "Prefix" field was actually a calculated field in my underlying Access table. For whatever reason, Access doesn't want to work with calculated fields with SQL; when I took out the calculation and just made the Prefix column a regular field, everything seems to work perfectly. I'm not really happy with this but it seems to work and that's what matters. Thanks to everyone who took the time to try and help me with this stuff. Cheers!
For some reason, when I pass the following query:
SELECT [313], [313 DE MINIMIS LIMIT]
FROM [Chem CAS INV]
WHERE [313 DE MINIMIS LIMIT] IS NULL AND 313 = '313'
SQL Server is returning rows that clearly don't match the conditions specified, as shown below:
I know that sometimes working with NULL can require a more in depth understanding of how SQL works (like when using IS NOT NULL with IN statements vs. NOT EXISTS, etc.), but I've done simple checks with NULL like this many times, and I can't understand why 313 would ignore a simple check for a string value.
I'm using SQL Server 2014 Express, and here are the datatypes that go with these columns:
I feel like I'm missing something obvious, but I can't understand what that would be.
313 = '313' is matching becaue SQL is thinking you meant the NUMBER 313 instead of your column [313]. You need to wrap it in brackets like you did the rest of your query. As a side note, this is one reason why naming a column a NUMBER is completely insane. You're going to have these bugs CONSTANTLY. Rename it something sensible like Val_313 or something else. You should think of the brackets as SQL Servers way of saying: "Are you sure you want to do this?" 99.99% of the time your answer your should be: no. :)
I am trying to write a CASE statement for a query, and it seems USQL doesn't actually have the Syntax for a CASE.
Just trying to find out if anyone knows of the correct fn to make a case statement.
Thanks
According to the documentation that I found (http://pz.southware.com/nlhtml/USQL_User_Guide.pdf) there is no reference to a CASE statement, so you're probably correct in saying that it doesn't support that.
There is the isnull function that you could use if your CASE statement condition was checking for a null value. You could maybe simulate a case by having a nested query or two, or maybe by splitting your query into multiple parts (one for each CASE condition) and then unioning them together. Not exactly elegant though...
I see this:
Project.update_all("cost = cost * 3",
"lower(technology) LIKE '%microsoft%'")
as an example of update_all method in Active Record when I'm following The Rails 3 Way, very simple phrase, huh? But I just can't figure out what do parentheses mean in lower(technology) here.
So, Could you tell me some possible answers? Because I don't know if there are some different situations we can use parentheses like this.
thanks.
They call the SQL LOWER function to lowercase the string.
LOWER technology
would be a syntax error, because LOWER is a function, not a keyword.
I suppose I have always naively assumed that scalar functions in the select part of a SQL query will only get applied to the rows that meet all the criteria of the where clause.
Today I was debugging some code from a vendor and had that assumption challenged. The only reason I can think of for this code failing is that the Substring() function is getting called on data that should have been filtered out by the WHERE clause. But it appears that the substring call is being applied before the filtering happens, the query is failing.
Here is an example of what I mean. Let's say we have two tables, each with 2 columns and having 2 rows and 1 row respectively. The first column in each is just an id. NAME is just a string, and NAME_LENGTH tells us how many characters in the name with the same ID. Note that only names with more than one character have a corresponding row in the LONG_NAMES table.
NAMES: ID, NAME
1, "Peter"
2, "X"
LONG_NAMES: ID, NAME_LENGTH
1, 5
If I want a query to print each name with the last 3 letters cut off, I might first try something like this (assuming SQL Server syntax for now):
SELECT substring(NAME,1,len(NAME)-3)
FROM NAMES;
I would soon find out that this would give me an error, because when it reaches "X" it will try using a negative number for in the substring call, and it will fail.
The way my vendor decided to solve this was by filtering out rows where the strings were too short for the len - 3 query to work. He did it by joining to another table:
SELECT substring(NAMES.NAME,1,len(NAMES.NAME)-3)
FROM NAMES
INNER JOIN LONG_NAMES
ON NAMES.ID = LONG_NAMES.ID;
At first glance, this query looks like it might work. The join condition will eliminate any rows that have NAME fields short enough for the substring call to fail.
However, from what I can observe, SQL Server will sometimes try to calculate the the substring expression for everything in the table, and then apply the join to filter out rows. Is this supposed to happen this way? Is there a documented order of operations where I can find out when certain things will happen? Is it specific to a particular Database engine or part of the SQL standard? If I decided to include some predicate on my NAMES table to filter out short names, (like len(NAME) > 3), could SQL Server also choose to apply that after trying to apply the substring? If so then it seems the only safe way to do a substring would be to wrap it in a "case when" construct in the select?
Martin gave this link that pretty much explains what is going on - the query optimizer has free rein to reorder things however it likes. I am including this as an answer so I can accept something. Martin, if you create an answer with your link in it i will gladly accept that instead of this one.
I do want to leave my question here because I think it is a tricky one to search for, and my particular phrasing of the issue may be easier for someone else to find in the future.
TSQL divide by zero encountered despite no columns containing 0
EDIT: As more responses have come in, I am again confused. It does not seem clear yet when exactly the optimizer is allowed to evaluate things in the select clause. I guess I'll have to go find the SQL standard myself and see if i can make sense of it.
Joe Celko, who helped write early SQL standards, has posted something similar to this several times in various USENET newsfroups. (I'm skipping over the clauses that don't apply to your SELECT statement.) He usually said something like "This is how statements are supposed to act like they work". In other words, SQL implementations should behave exactly as if they did these steps, without actually being required to do each of these steps.
Build a working table from all of
the table constructors in the FROM
clause.
Remove from the working table those
rows that do not satisfy the WHERE
clause.
Construct the expressions in the
SELECT clause against the working table.
So, following this, no SQL dbms should act like it evaluates functions in the SELECT clause before it acts like it applies the WHERE clause.
In a recent posting, Joe expands the steps to include CTEs.
CJ Date and Hugh Darwen say essentially the same thing in chapter 11 ("Table Expressions") of their book A Guide to the SQL Standard. They also note that this chapter corresponds to the "Query Specification" section (sections?) in the SQL standards.
You are thinking about something called query execution plan. It's based on query optimization rules, indexes, temporaty buffers and execution time statistics. If you are using SQL Managment Studio you have toolbox over your query editor where you can look at estimated execution plan, it shows how your query will change to gain some speed. So if just used your Name table and it is in buffer, engine might first try to subquery your data, and then join it with other table.