sql give list of numbers in where clause - sql

I was looking at this example. This makes it look like single quotes are not required in the where clause when you give a list of numbers. I am using an oracle database if that makes a difference.
https://www.sqlservertutorial.net/sql-server-basics/sql-server-in/
SELECT
product_name,
list_price
FROM
production.products
WHERE
list_price IN (89.99, 109.99, 159.99)
ORDER BY
list_price;
So why is toad complaining when I do this? It says invalid identifier as the error message.
This is the query that fails.
select * from table1 where id in (1, 2, 3, 4);
Toad does not complain when I do this.
select * from table1 where id in ('1', '2', '3', '4');

Check to make sure you are using your expected datatype. In my case I was using CHAR(12) thats why I needed quotes.
SELECT
COLUMN_NAME,
DATA_TYPE,
DATA_LENGTH,
DATA_PRECISION,
DATA_SCALE
FROM ALL_TAB_COLS
Where TABLE_NAME = 'table1';
If that doesn't work your table may be in capital letters so try this.
SELECT
COLUMN_NAME,
DATA_TYPE,
DATA_LENGTH,
DATA_PRECISION,
DATA_SCALE
FROM ALL_TAB_COLS
Where TABLE_NAME = upper('table1');

Since the question was about fetching different numbers, let's have a look on an easy way to do this.
Of course, if the column always holds numbers only and strings should not be allowed, we should just change its datatype.
And of course, if we just want to check for a few numbers like 1,2 and 3, we can use an IN clause like shown in the question.
But let's assume we can't change the datatype because also strings can occur and we need to accept a big range of numbers.
For example, we want to accept all numbers between 200 and 300. We dislike to write an IN clause with 101 values, don't we?
So we can use VALIDATE_CONVERSION to make sure we consider numeric entries only.
Then we use CAST AS INT to check the number should be between 200 and 300.
The query will be this one:
SELECT id
FROM table1
WHERE VALIDATE_CONVERSION(id AS NUMBER) = 1
AND CAST (id AS INT) BETWEEN 200 AND 300
ORDER BY id; -- sorting is of course not needed. Remove it if not intended.
We can try this out here: db<>fiddle

Related

How to filter out null values

The results of my SQL query include null values. How do I filter out null values?
The syntax may vary depending on the database you are using but you can explicitly exclude nulls in the where clause. For example, the following will exclude null values in the primary_author field:
SELECT
date,
primary_author,
ISBN
FROM
books
WHERE
primary_author IS NOT NULL;
My example works on every database I know, so it should work for you =)
SELECT *
FROM TABLE_NAME
WHERE COLUMN_NAME IS NOT NULL
Here you can find a simple explanation and some examples: https://www.w3schools.com/sql/sql_null_values.asp
But some times you want to replace null values for a default value, like 'X', in this case, we should know the database for correct syntax, here some examples:
Oracle:
SELECT nvl(column_name,'X')
FROM TABLE_NAME
Sqlite:
SELECT ifnull(column_name,'X')
FROM TABLE_NAME
SqlServer:
SELECT coalesce(column_name,'X')
FROM TABLE_NAME

How to perform Like in SQL on a column with '%' in the data?

I am using oracle database and writing the likeness filter for the persistence layer and want to perform likeness on a column that can possibly have '%' in it's data.
To filter data I am writing the query for likeness using LIKE clause as
select * from table where columnName like '%%%';
which is returning all the values but I only want the rows that contains '%' in the columnName.
Not sure what escape character to use or what to do to filter on the '%' symbol. Any suggestions??
Also, I have to do the same thing using Criteria api in java and have no clues about putting escape character there.
You can use an escape character.
where columnName like '%$%%' escape '$'
REGEXP_LIKE might help in a rather simple manner.
SQL> with test (col) as
2 (select 'abc%def' from dual union all
3 select '%12345&' from dual union all
4 select '%abc12%' from dual union all
5 select '1234567' from dual
6 )
7 select *
8 from test
9 where regexp_like(col, '%');
COL
-------
abc%def
%12345&
%abc12%
SQL>
If I have understood it correctly the answer from the #Littlefoot is correct(and I will up-vote it now). I will just add more details because you are looking for name of the columns of your table "I only want the rows that contains '%' in the columnName".
Here is the table I have created:
CREATE TABLE "table_WITH%" ("numer%o" number
, name varchar2(50)
, "pric%e" number
, coverage number
, activity_date date);
Then this query gives me the correct answer:
SELECT column_name
FROM ALL_TAB_COLUMNS
WHERE TABLE_NAME = 'table_WITH%'
AND regexp_like(COLUMN_NAME, '%');
Gordon's answer using the escape clause of the like command is correct in the general case.
In your specific case (searching for a single character, anywhere in a string), a simpler method is to use instr, e.g.
where instr(columnname, '%') > 0

Select the rows where variable x starts with 65 (teradata)

I have a table with a column named x that includes numbers for all my observations. I now want to select only the variables that start with 65.
I've tried:
SELECT * FROM table
WHERE x REGEXP '^[65]'
and different versions of like/isnumeric, but I cant figure a clean way out.
If this is actually a Teradata DBMS your inital query will result in an error message because there's no REGEXP (but there's a REGEXP_SIMILAR).
You don't need a regular expression to compare the first two digits. If the datatype of x is numeric you must cast it to a string first:
WHERE TRIM(x) LIKE '65%'
WHERE CAST(x AS VARCHAR(20)) LIKE '65%'
If it's a VarChar you might have some leading spaces (which are really bad):
WHERE TRIM(x) LIKE '65%'
You may use like or left to find start with prefix
SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE '65%'
or
SELECT * FROM TABLE_NAME WHERE LEFT(COLUMN_NAME, 2) = '65'
Tested and working.
SELECT * FROM someTable WHERE concat("_",x) like '_65%'
Could be slow if your table is very big, because it does not use the indexes and performs full table scan.

Need SQL query which accepts EMPTY values in IN 'clause'

I am newbie to the SQL.
I have a requirement where users might select any values from any of the 3 'multiple list' dropdown box. There might be cases where user can completely ignore any of the dropdown box out of the 3.
So i need a query which can handle that.
The equivalent select query with values looks like this.
SELECT * FROM TABLE WHERE
description1 LIKE '%SHK ABS%' OR
description2 LIKE '%SHK ABS%' OR
description3 LIKE '%SHK ABS%' OR
description4 LIKE '%SHK ABS%' and
**Year** in ('2017','2016') and
**Program** in ('CDPGM');
Problem:
I tried a lot but not able to write a query which accepts empty values in 'IN' clause.
Example: If user dint select any year and program, then empty values will be passed. Basically the query should act like it will ignore that columns in where clause.
Any idea how to achieve this ?
From what you posted I'm guessing you have a problem defining the blank value.
SELECT * FROM table
WHERE col_name IS NULL OR
col_name IN (<list_of_your_values>, '', 0,)
As per I understand there can be three type of empty values according to your case: NULL, Blank and Space(s).
The in clause to match those will look like:
SELECT * FROM table_name WHRE col_name in (null, '', <your other values>);
I have tested it in MySQL 5.6(latest version). For other versions/DBMSs you may need to use trim function:
SELECT * FROM table_name WHRE trim(col_name) in (null, '', <your other values>);
Edit:
For integer type column the empty valuea will be NULL only, OR you can also treat 0 as empty value:
SELECT * FROM table_name WHRE col_name in (null, 0, <your other values>);

Use sql to select data, then insert row in first position of result set only (not update database)

If I select a column in a table, say 10 rows, can I use SQL to insert a 'please select' row into the first position using SQL only? I want to insert it in the result set only - not the database.
First you should know this is a bad idea.
You are confusing your presentation layer and your database layer. Forcing SQL to do things like output status messages or feedback to users is an antipattern to be avoided.
That being said, if the column is of a string type (char, varchar, etc), you can do something like:
SELECT 'Please Select'
UNION ALL
SELECT TOP 10 Varcharfield
FROM Mytable
If it's numeric then no unless you cast it to a string type.
Here's something you can try:
SELECT u.YourVarcharColumnName
FROM (
SELECT 1 AS rID, 'Please select' AS YourVarcharColumnName
UNION
SELECT 2 AS rID, YourVarcharColumnName
FROM YourTableName
) u
ORDER BY u.rID;
I placed rID in place and sorted by it as an extreme-case-measure when your intended first rowset does not come out on top...
However, you should keep in mind that YourVarcharColumnName should be (as it says) a string. You'll have to convert it to a string if it's a non-string column.
As #JNK mentioned it.. I thought I should edit my post as well:
Please first try:
SELECT 'Please select' AS YourVarcharColumnName
UNION
SELECT YourVarcharColumnName
FROM YourTableName
Which is similar to what the others have posted. If you ever experience what I've been unfortunate to encounter and 'Please select' doesn't come out on top, please refer to the query I posted at the top.. Thanks!
SELECT '(Please select)'
UNION
SELECT ColumnName FROM TableName