How SQL selects between two strings/texts? - sql

In SQL if I've the following select statement:
SELECT * FROM Products WHERE ProductName BETWEEN 'Geitost' AND 'Pavlova'
It run successfully and display the output records, but I'm a little bit confusing about how we can search between two strings and how the SQL perform it,
for example the following select statement:
SELECT * FROM Products WHERE Price BETWEEN 100 AND 300
It's clear that we are trying to find all the prices which has a price equals to 100$ or greater but less than or equals 300$
Can somebody explain what is the selecting mechanism between two strings in SQL?
Thanks in advance.

Your question is rather baffling. This code works:
WHERE Price BETWEEN 100 AND 300
It is turned into:
WHERE Price >= 100 AND Price <= 300
Similarly, your first condition is equivalent to:
WHERE ProductName >= 'Geitost' AND
ProductName <= 'Pavlova'
So the question is about how strings are compared. The short answer is "how they appear in the dictionary". Of course, there are lots of dictionaries in the world. The more complete answer is based on collations, which describe the alphabetic ordering of strings.
Here is the MySQL documentation for collations and character sets. Although some details such as the names of the collations and the syntax for functions may vary, the idea is similar across databases.

Related

How to query column with letters on SQL?

I'm new to this.
I have a column: (chocolate_weight) On the table : (Chocolate) which has g at the end of every number, so 30x , 2x5g,10g etc.
I want to remove the letter at the end and then query it to show any that weigh greater than 35.
So far I have done
Select *
From Chocolate
Where chocolate_weight IN
(SELECT
REPLACE(chocolote_weight,'x','') From Chocolate) > 35
It is coming back with 0 , even though there are many that weigh more than 35.
Any help is appreciated
Thanks
If 'g' is always the suffix then your current query is along the right lines, but you don't need the IN you can do the replace in the where clause:
SELECT *
FROM Chocolate
WHERE CAST(REPLACE(chocolate_weight,'g','') AS DECIMAL(10, 2)) > 35;
N.B. This works in both the tagged DBMS SQL-Server and MySQL
This will fail (although only silently in MySQL) if you have anything that contains units other than grams though, so what I would strongly suggest is that you fix your design if it is not too late, store the weight as an numeric type and lose the 'g' completely if you only ever store in grams. If you use multiple different units then you may wish to standardise this so all are as grams, or alternatively store the two things in separate columns, one as a decimal/int for the numeric value and a separate column for the weight, e.g.
Weight
Unit
10
g
150
g
1000
lb
The issue you will have here though is that you will have start doing conversions in your queries to ensure you get all results. It is easier to do the conversion once when the data is saved and use a standard measure for all records.

SQL Server Floating Point in WHERE clause

I'm trying to query a database, I need to get a list of customers where their weight is equal to 60.5. The problem is that 60.5 is a real I've never query a database with a real in a where clause before.
I've tried this:
SELECT Name FROM Customers WHERE Weight=60.5
SELECT Name FROM Customers WHERE Weight=cast(60.5 as real)
SELECT Name FROM Customers WHERE Weight=cast(60.5 as decimal)
SELECT Name FROM Customers WHERE Weight=convert(real,'60.5')
SELECT Name FROM Customers WHERE Weight=convert(decimal,'60.5')
These queries return 0 values but in the Customers table their are 10 rows with Weight=60.5
Your problem is that floating point numbers are inaccurate by definition. Comparing what seems to be 60.5 to a literal 60.5 might not work as you've noticed.
A typical solution is to measure the difference between 2 values, and if it's smaller then some predefined epsilon, consider them equal:
SELECT Name FROM Customers WHERE ABS(Weight-60.5) < 0.001
For better performance, you should actually use:
SELECT Name FROM Customers WHERE Weight BETWEEN 64.999 AND 65.001
If you need equality comparison, you should change the type of the column to DECIMAL. Decimal numbers are stored and compared exactly, while real and float numbers are approximations.
#Amit's answer will work, but it will perform quite poorly in comparison to my approach. ABS(Weight-60.5) < 0.001 is unable to use index seeks. But if you convert the column to DECIMAL, then Weight=60.5 will perform well and use index seeks.

String ending in range of numbers

I have a column with data of the following structure:
aaa5644988
aaa4898494
aaa5642185
aaa5482312
aaa4648848
I have a range that can be anything, like 100-30000 or example. I want to have all values that end in numbers between that range.
I tried
like '%[100-30000]'
but this doesn't work apparently.
I have seen a lot of similar questions but none of the solved my problem
edit I'm using SQL server 2008
Example:
Value
aaa45645695
aaa28568720
aaa65818450
8789212
6566700
For the range 600-1200, I want to retrieve row 1,2,5 because they end with the range.
In SQL, like normally only support % and _ these two operators. That's why like '%[100-30000]' doesn't work.
Depend on your use case, there could be two solutions for this problem:
If you only need to do this query two or three times(didn't care how long it takes), or the dataset is not very big. You can select all the data from this column, and then do the filtering in another programming language.
Take ruby for example, you can do:
column_data = #connection.execute("select * from your_column_name")
result = column_data.map{|x| x.gsub(/^.*[^\d]/, '').to_i }.select{|x| x > 100 && x < 30000}
If you need to do this query regularly, I'd suggest you add a new column to this data table with only the numbers in the current column, so as to get a much better performance in querying speed.
SELECT *
FROM your_table
WHERE number_column BETWEEN 100 AND 30000

Joining Tables in Oracle 8i to Limit Results

My background in SQL is limited, but my Googling isn't, I feel that I might just be missing the vocabulary to ask this question properly so hopefully beyond an answer to my question I can get the vocabulary I need to research this issue further.
I have a parts table - PARTS
I have a Purchase Order table - PO
and I have a PO Line Item table - PO_LINEITEM
The question I'm attempting to answer is given a particular part I want to get the latest purchase order and then look at the price we paid.
The PO table holds the date (PO_DATE) of when the Purchase Order was filled and the PO_LINEITEM table holds the information regarding the particular line item such as part primary key (PART_PRIMARYKEY) and price (PART_PRICE). The PARTS table isn't as important as the rest except that I need to return a PART primary key so that I can base the resulting view off the PARTS table
I've been through sub-queries and scalable sub-queries and the like, but I can't seem to find the right combination.
I started from a base of:
SELECT a.PO_DATE, b.PART_PRIMARYKEY, b.PART_PRICE
FROM PO a, PO_LINEITEM b
WHERE a.PO_PRIMARYKEY = b.PO_PRIMARYKEY
As you would expect this returns a list of every instance of an object in a PO with it's price and the date the Purchase Order was filled. The closest I have come to crack this is by using the MAX function on the date such as:
SELECT MAX(a.PO_DATE) AS DATE, b.PART_PRIMARYKEY, b.PART_PRICE
FROM PO a, PO_LINEITEM b
WHERE a.PO_PRIMARYKEY = b.PO_PRIMARYKEY
GROUP BY b.PART_PRIMARYKEY, b.PART_PRICE
This returns a Max date for each price a we paid for a particular part, so:
PART 1234, £12.95, 12/08/2012
PART 1234, £13.00, 14/08/2012
PART 1234. £11.15, 17/08/2012
PART 2345, £5.25, 12/08/2012
PART 2345, £5.65, 13/08/2012
etc.
What I need is:
PART 1234, £11.15, 17/08/2012
PART 2345. £5.65, 13/08/2012
If I could just group by the PART_PRIMARYKEY that would be excellent, but I get an ORA-00979 not a GROUP BY expression when I try.
Like I said I feel that my lack of vocabulary around this issue is impeding me finding an answer, so if anyone could point me in the right direction I'd be grateful
So hopefully I'm not asking a question that is asked every other day, but haven't found because I didn't use the magical combination of words to find.
Thank you for any help you can offer.
Look up Analytic Functions. They were introduced in 8i though I'm not sure how advanced they were at the time compared to how very good they can be in 11. A few links that I've used to understand them:
http://www.oracle-base.com/articles/misc/analytic-functions.php
http://www.orafaq.com/node/55
Though, a sub-query such as this might suffice (I may have your column naming mixed up):
select A.PART_PRIMARYKEY, B.PART_PRICE, A.PO_DATE
from PO A, PO_LINEITEM B
where A.PO_PRIMARYKEY = B.PO_PRIMARYKEY
and (A.PART_PRIMARYKEY, A.PO_DATE) in
( select A.PART_PRIMARYKEY, max(A.PO_DATE)
from PO A, PO_LINEITEM B
where A.PO_PRIMARYKEY = B.PO_PRIMARYKEY
group by A.PART_PRIMARYKEY);

Vague count in sql select statements

I guess this has been asked in the site before but I can't find it.
I've seen in some sites that there is a vague count over the results of a search. For example, here in stackoverflow, when you search a question, it says +5000 results (sometimes), in gmail, when you search by keywords, it says "hundreds" and in google it says aprox X results. Is this just a way to show the user an easy-to-understand-a-huge-number? or this is actually a fast way to count results that can be used in a database [I'm learning Oracle at the moment 10g version]? something like "hey, if you get more than 1k results, just stop and tell me there are more than 1k".
Thanks
PS. I'm new to databases.
Usually this is just a nice way to display a number.
I don't believe there is a way to do what you are asking for in SQL - count does not have an option for counting up until some number.
I also would not assume this is coming from SQL in either gmail, or stackoverflow.
Most search engines will return a total number of matches to a search, and then let you page through results.
As for making an exact number more human readable, here is an example from Rails:
http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human
With Oracle, you can always resort to analytical functions in order to calculate the exact number of rows about to be returned. This is an example of such a query:
SELECT inner.*, MAX(ROWNUM) OVER(PARTITION BY 1) as TOTAL_ROWS
FROM (
[... your own, sorted search query ...]
) inner
This will give you the total number of rows for your specific subquery. When you want to apply paging as well, you can further wrap these SQL parts as such:
SELECT outer.* FROM (
SELECT * FROM (
SELECT inner.*,ROWNUM as RNUM, MAX(ROWNUM) OVER(PARTITION BY 1) as TOTAL_ROWS
FROM (
[... your own, sorted search query ...]
) inner
)
WHERE ROWNUM < :max_row
) outer
WHERE outer.RNUM > :min_row
Replace min_row and max_row by meaningful values. But beware that calculating the exact number of rows can be expensive when you're not filtering using UNIQUE SCAN or relatively narrow RANGE SCAN operations on indexes. Read more about this here: Speed of paged queries in Oracle
As others have said, you can always have an absolute upper limit, such as 5000 to your query using a ROWNUM <= 5000 filter and then just indicate that there are more than 5000+ results. Note that Oracle can be very good at optimising queries when you apply ROWNUM filtering. Find some info on that subject here:
http://www.dba-oracle.com/t_sql_tuning_rownum_equals_one.htm
Vague count is a buffer which will be displayed promptly. If user wants to see more results then he can request more.
It's a performance facility, after displaying the results the sites like google keep searching for more results.
I don't know how fast this will run, but you can try:
SELECT NULL FROM your_tables WHERE your_condition AND ROWNUM <= 1001
If count of rows in result will equals to 1001 then total count of records will > 1000.
this question gives some pretty good information
When you do an SQL query you can set a
LIMIT 0, 100
for example and you will only get the first hundred answers. so you can then print to your viewer that there are 100+ answers to their request.
For google I couldn't say if they really know there is more than 27'000'000'000 answer to a request but I believe they really do know. There are some standard request that have results stored and where the update is done in the background.