Meaning of some parentheses in SQL - sql

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.

Related

Difference between Placeholder and parameter

I was watching a course about JDBC and when the Instructor was speaking about ? (Question Mark) in Prepared Statement, he said:
Before I execute the Query, I have to fill in the placeholders or parameters.
he was talking about a query like this:
SELECT * FROM Employee where salary > ?
Now, my main question is:
what is difference between placeholder and parameter?
and isn't he wrong? can ? be either placeholder or parameter?
Edit:
I consider these two definition also:
argument is the value/variable/reference being passed in, parameter is the receiving variable
There is no difference, these are just two terms used for the same things. Which is probably why that phrase was used: to introduce both terms and indicate they can be used interchangeably. There is even a third variant where both are combined in a single term: parameter placeholder.
As I see it, the ? is a placeholder for a value, but at the same time a parameter for the query.

DB2 complex like

I have to write a select statement following the following pattern:
[A-Z][0-9][0-9][0-9][0-9][A-Z][0-9][0-9][0-9][0-9][0-9]
The only thing I'm sure of is that the first A-Z WILL be there. All the rest is optional and the optional part is the problem. I don't really know how I could do that.
Some example data:
B/0765/E 3
B/0765/E3
B/0764/A /02
B/0749/K
B/0768/
B/0784//02
B/0807/
My guess is that I best remove al the white spaces and the / in the data and then execute the select statement. But I'm having some problems writing the like pattern actually.. Anyone that could help me out?
The underlying reason for this is that I'm migrating a database. In the old database the values are just in 1 field but in the new one they are splitted into several fields but I first have to write a "control script" to know what records in the old database are not correct.
Even the following isn't working:
where someColumn LIKE '[a-zA-Z]%';
You can use Regular Expression via xQuery to define this pattern. There are many question in StackOverFlow that talk about patterns in DB2, and they have been solved with Regular Expressions.
DB2: find field value where first character is a lower case letter
Emulate REGEXP like behaviour in SQL

CodeIgniter: meaning of backquotes in CI query

The book "CodeIgniter 1.7 Professional Development" has the following
example in the "Using Callbacks" section of Chapter 3.
$query = $this->db->
query("SELECT * FROM `user_data` WHERE `email` = '$email'");
What is the meaning of or function of the backquotes around the
table name or field name in this example? What do the backquotes do?
Thanks.
Also, another example in the book has the following:
$query = $this->db->query('SELECT * FROM 'users'');
Are the forward quotes the same as the backquotes in this context?
Are these constructs standard SQL compliant?
Thanks.
The backquotes simply say "this is not an SQL reserved keyword". They also theoretically allow using spaces and special characters in table names, although why you would want to do that is beyond good practice sanity.
Using them is generally recommended though to avoid ambiguity with column names like 'name', 'limit' or 'count'.
It's not a Codeigniter thing, but an SQL one.
You wouldn't use them in CI anyway, if you'd use active records. The framework will handle the escapes and stuff, so you don't have to think about these things - that's one of the reason why you use backquotes in queries.

Performing an ASP.NET database search with StartsWith keyword

I have a query. I am developing a site that has a search engine. The search engine is the main function. It is a business directory site.
A present I have basic search sql that searches the database using the "LIKE" keyword.
My client has asked me to change the search function so instead of using the "Like" keyword they are after something along the lines of the "Startswith" keyword.
To clarify this need here is an example.
If somebody types "plu" for plumbers in the textbox it currently returns, e.g.,
CENTRE STATE PLUMBING & ROOFING
PLUMBING UNLIMITED
The client only wants to return the "PLUMBING UNLIMITED" because it startswith "plu", and doesn't "contain" "plu"
I know this is a weird and maybe silly request, however does anyone have any example SQL code to point me in the right direction on how to achieve this goal.
Any help would be greatly appreciated, thanks...
how about this:
SELECT * FROM MyTable WHERE MyColumn LIKE 'PLU%'
please note that the % sign is only on the right side of the string
example in MS SQL
Instead of:
select * from professions where name like '%plu%'
, use a where clause without the leading %:
select * from professions where name like 'plu%'
LIKE won't give you the performance you need for a really effective search. Looking into something like Lucence or your engine's Full Text Search equivalent.

Regular expression to match common SQL syntax?

I was writing some Unit tests last week for a piece of code that generated some SQL statements.
I was trying to figure out a regex to match SELECT, INSERT and UPDATE syntax so I could verify that my methods were generating valid SQL, and after 3-4 hours of searching and messing around with various regex editors I gave up.
I managed to get partial matches but because a section in quotes can contain any characters it quickly expands to match the whole statement.
Any help would be appreciated, I'm not very good with regular expressions but I'd like to learn more about them.
By the way it's C# RegEx that I'm after.
Clarification
I don't want to need access to a database as this is part of a Unit test and I don't wan't to have to maintain a database to test my code. which may live longer than the project.
Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. It can be demonstrated you can't validate SQL with a regex. So, you can stop trying.
SQL is a type-2 grammar, it is too powerful to be described by regular expressions. It's the same as if you decided to generate C# code and then validate it without invoking a compiler. Database engine in general is too complex to be easily stubbed.
That said, you may try ANTLR's SQL grammars.
As far as I know this is beyond regex and your getting close to the dark arts of BnF and compilers.
http://savage.net.au/SQL/
Same things happens to people who want to do correct syntax highlighting. You start cramming things into regex and then you end up writing a compiler...
I had the same problem - an approach that would work for all the more standard sql statements would be to spin up an in-memory Sqlite database and issue the query against it, if you get back a "table does not exist" error, then your query parsed properly.
Off the top of my head: Couldn't you pass the generated SQL to a database and use EXPLAIN on them and catch any exceptions which would indicate poorly formed SQL?
Have you tried the lazy selectors. Rather than match as much as possible, they match as little as possible which is probably what you need for quotes.
To validate the queries, just run them with SET NOEXEC ON, that is how Entreprise Manager does it when you parse a query without executing it.
Besides if you are using regex to validate sql queries, you can be almost certain that you will miss some corner cases, or that the query is not valid from other reasons, even if it's syntactically correct.
I suggest creating a database with the same schema, possibly using an embedded sql engine, and passing the sql to that.
I don't think that you even need to have the schema created to be able to validate the statement, because the system will not try to resolve object_name etc until it has successfully parsed the statement.
With Oracle as an example, you would certainly get an error if you did:
select * from non_existant_table;
In this case, "ORA-00942: table or view does not exist".
However if you execute:
select * frm non_existant_table;
Then you'll get a syntax error, "ORA-00923: FROM keyword not found where expected".
It ought to be possible to classify errors into syntax parsing errors that indicate incorrect syntax and errors relating to tables name and permissions etc..
Add to that the problem of different RDBMSs and even different versions allowing different syntaxes and I think you really have to go to the db engine for this task.
There are ANTLR grammars to parse SQL. It's really a better idea to use an in memory database or a very lightweight database such as sqlite. It seems wasteful to me to test whether the SQL is valid from a parsing standpoint, and much more useful to check the table and column names and the specifics of your query.
The best way is to validate the parameters used to create the query, rather than the query itself. A function that receives the variables can check the length of the strings, valid numbers, valid emails or whatever. You can use regular expressions to do this validations.
public bool IsValid(string sql)
{
string pattern = #"SELECT\s.*FROM\s.*WHERE\s.*";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
return rgx.IsMatch(sql);
}
I am assuming you did something like .\* try instead [^"]* that will keep you from eating the whole line. It still will give false positives on cases where you have \ inside your strings.