How can I write this?
A delete statement to remove all records from the TableA table where the LastName starts with ba and they have a phone number in the 3 area code.
DELETE
FROM TableA
WHERE LastName = 'ba' AND PhoneNumber = '3';
Assuming the phone number column be text, then we can use LIKE comparisons as follows:
DELETE
FROM TableA
WHERE LastName LIKE 'Ba%' OR LastName LIKE 'ba%' OR PhoneNumber LIKE '3%';
MySQL, SQL Server, PostgreSQL, SQLite are all completely different database products. In all of them though, matching a pattern is done using LIKE, not =. To match a value that starts with a certain prefix you use LIKE 'something%'
% matches any character. It's the equivalent of * in a file search or .* in a regular expression.
DELETE FROM TableA
WHERE LastName LIKE 'ba%' AND PhoneNumber LIKE '3%'
Different databases have different case-sensitivity (collation) rules though.
In SQL Server and MySQL, case-insensitive sorting and searching is most common, so LIKE 'ba%' will match both Ba and ba.
In PostgreSQL, the norm is case-sensitive matching. You may have to use [Bb]a% in that case, to match either B or b
Related
The records I am querying for are kept in 2 different formats. Each person has at least 1 record of their email in the format John.Doe#abc.com. Some people have a second record in which their email is DoeJ#abc.com.
How can I query for the records in which the email is formatted like John.Doe#abc.com?
I attempted to do it with the following SQL Statement but I it returns an empty result:
Select * from email where regexp_like(emailaddress, '. (#)')
The end product will be used in a join with a few other Queries, so selecting distinct values is not an option here. The environment is an Oracle DB, and because this will be done through multiple joins, the more efficient it is the better. Does anyone have any ideas what I am doing wrong, or other ways to accomplish this?
Thank you,
Joshua
You can use REGEXP_LIKE:
Select * from email where regexp_like(emailaddress, '\S*\.\S*\#\S*\.\S*')
Use "\S*" to match all non-whitespace characters
Or just a regular LIKE:
Select * from email where emailaddress LIKE '%.%#%.%'
Not sure what characters are included in the % placeholder in Oracle, so you should test it out.
The REGEXP one will give you tighter control over the pattern matching.
Let me know if it works.
How about using like?
where emailaddress like '%.%#%'
The first format seems distinguished by having a period before the ampersand.
I am currently making a program in c# that uses SQL queries. I am new to SQL and would like some help on a matter.
Is it possible for a specific position in a string to be queried?
Eg. SELECT ID FROM Names WHERE Firstname[0] = "J" AND Lastname = "Doe"
If anything is unclear please let me know, any help is appreciated, thank you.
Yes, you can, but rather like this
SELECT ID
FROM Names
WHERE Firstname LIKE 'J%' AND Lastname = 'Doe';
Notes:
In SQL, strings should be delimited with single quotes.
The LIKE operation has a pattern. The pattern says the first character is J; % is a wildcard that matches 0 or more characters.
Databases generally do not have a built-in array types that are compatible across databases. Further, no databases (as far as I know) , treats strings as arrays of characters. These concepts are somewhat foreign to SQL (although some databases do support arrays).
You could use LIKE in WHERE clause.
example:-
SELECT ID FROM Names WHERE Firstname LIKE "J%" AND Lastname = "Doe"
you can use keyword 'like' for example : WHERE names LIKE 'a%' it will return all name starting with character 'a'. like wise '%a'it will return all names ending with 'a'.
I want to select rows where column [Name] contains ONLY Cyrillic characters in UPPERCASE, and comma and hyphen from the table using LIKE :
SELECT *
FROM Clients
WHERE NAME LIKE '%[А-Я][,-]%' COLLATE Cyrillic_General_CS_AS
Or using explicit pattern:
SELECT *
FROM Clients
WHERE NAME LIKE '%[АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ][,-]%' COLLATE Cyrillic_General_CS_AS
But these selects rows in which at least one character exists in pattern (but allows any other characters not exists in pattern).
Maybe using ^ (NOT predicate) excluding any other characters like this:
SELECT *
FROM Clients
WHERE NAME LIKE '%[^A-Z][./=+]%' COLLATE Cyrillic_General_CS_AS
But this requires enumeration a large number of unnecessary characters.
How best to make a selection?
Use a double negative. Search for rows where the column doesn't contain at least one character not in the set you're interested in:
SELECT *
FROM Clients
WHERE NAME NOT LIKE '%[^-АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ,]%' COLLATE Cyrillic_General_CS_AS
(I'm not quite sure what you were attempting to do by placing the hyphen and comma in a separate grouping, but I've moved them into the same group for now, since that seems to make some sense)
I needed some guidance as to how I can exlude rows that contains any form of letter in a cell that is supposed to contain integers only.
This is what the data looks like now:
CustomerID
----------
ea176680
27906857
62675436
62566247
1bed413e
61110053
61113323
34441416
AS you can see in the table, the first,ID contains letters. How can I remove complete rows if a cell were to contain any form of letters?
How about this where clause?
where CustomerId not like '%[^0-9]%'
It filters out any values that have a non-digit. Unfortunately, SQL Server doesn't support regular expressions, but this will do what you want.
If you specifically wanted to look for letters, you can do:
where CustomerId like '%[a-zA-Z]%'
SQL Server can match on a specific pattern in your statement using like. It looks somewhat like regex, but isn't exactly that.
Use this statement if you want to match on all CustomerIds that contains characters in the range A-Z and a-z:
select *
from table
where CustomerID like '%[A-za-z]%'
I am new to SQL programming.
I have a table job where the fields are id, position, category, location, salary range, description, refno.
I want to implement a keyword search from the front end. The keyword can reside in any of the fields of the above table.
This is the query I have tried but it consist of so many duplicate rows:
SELECT
a.*,
b.catname
FROM
job a,
category b
WHERE
a.catid = b.catid AND
a.jobsalrange = '15001-20000' AND
a.jobloc = 'Berkshire' AND
a.jobpos LIKE '%sales%' OR
a.jobloc LIKE '%sales%' OR
a.jobsal LIKE '%sales%' OR
a.jobref LIKE '%sales%' OR
a.jobemail LIKE '%sales%' OR
a.jobsalrange LIKE '%sales%' OR
b.catname LIKE '%sales%'
For a single keyword on VARCHAR fields you can use LIKE:
SELECT id, category, location
FROM table
WHERE
(
category LIKE '%keyword%'
OR location LIKE '%keyword%'
)
For a description you're usually better adding a full text index and doing a Full-Text Search (MyISAM only):
SELECT id, description
FROM table
WHERE MATCH (description) AGAINST('keyword1 keyword2')
SELECT
*
FROM
yourtable
WHERE
id LIKE '%keyword%'
OR position LIKE '%keyword%'
OR category LIKE '%keyword%'
OR location LIKE '%keyword%'
OR description LIKE '%keyword%'
OR refno LIKE '%keyword%';
Ideally, have a keyword table containing the fields:
Keyword
Id
Count (possibly)
with an index on Keyword. Create an insert/update/delete trigger on the other table so that, when a row is changed, every keyword is extracted and put into (or replaced in) this table.
You'll also need a table of words to not count as keywords (if, and, so, but, ...).
In this way, you'll get the best speed for queries wanting to look for the keywords and you can implement (relatively easily) more complex queries such as "contains Java and RCA1802".
"LIKE" queries will work but they won't scale as well.
Personally, I wouldn't use the LIKE string comparison on the ID field or any other numeric field. It doesn't make sense for a search for ID# "216" to return 16216, 21651, 3216087, 5321668..., and so on and so forth; likewise with salary.
Also, if you want to use prepared statements to prevent SQL injections, you would use a query string like:
SELECT * FROM job WHERE `position` LIKE CONCAT('%', ? ,'%') OR ...
I will explain the method i usally prefer:
First of all you need to take into consideration that for this method you will sacrifice memory with the aim of gaining computation speed.
Second you need to have a the right to edit the table structure.
1) Add a field (i usually call it "digest") where you store all the data from the table.
The field will look like:
"n-n1-n2-n3-n4-n5-n6-n7-n8-n9" etc.. where n is a single word
I achieve this using a regular expression thar replaces " " with "-".
This field is the result of all the table data "digested" in one sigle string.
2) Use the LIKE statement %keyword% on the digest field:
SELECT * FROM table WHERE digest LIKE %keyword%
you can even build a qUery with a little loop so you can search for multiple keywords at the same time looking like:
SELECT * FROM table WHERE
digest LIKE %keyword1% AND
digest LIKE %keyword2% AND
digest LIKE %keyword3% ...
You can find another simpler option in a thread here: Match Against.. with a more detail help in 11.9.2. Boolean Full-Text Searches
This is just in case someone need a more compact option. This will require to create an Index FULLTEXT in the table, which can be accomplish easily.
Information on how to create Indexes (MySQL): MySQL FULLTEXT Indexing and Searching
In the FULLTEXT Index you can have more than one column listed, the result would be an SQL Statement with an index named search:
SELECT *,MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*') as relevance FROM `documents`USE INDEX(search) WHERE MATCH (`column`) AGAINST('+keyword1* +keyword2* +keyword3*' IN BOOLEAN MODE) ORDER BY relevance;
I tried with multiple columns, with no luck. Even though multiple columns are allowed in indexes, you still need an index for each column to use with Match/Against Statement.
Depending in your criterias you can use either options.
I know this is a bit late but what I did to our application is this. Hope this will help someone tho. But it works for me:
SELECT * FROM `landmarks` WHERE `landmark_name` OR `landmark_description` OR `landmark_address` LIKE '%keyword'
OR `landmark_name` OR `landmark_description` OR `landmark_address` LIKE 'keyword%'
OR `landmark_name` OR `landmark_description` OR `landmark_address` LIKE '%keyword%'