I have two tables in a database. Contacts and Filter
In Contacts, I have ID, Name, and Email as the fields.
in Filter, I have ID and code
My objective is to be able to query the entire table and export a list that has been filtered by items in the Filter table. (basically the same that could be achieved with a grep -i -Ev ) ... Basically I want to filter out gmail or yahoo or others).
So if I do
select distinct email from contacts where email not like '%gmail%'
One level of the filter works.
but if I do,
select distinct email from contacts where email not like '%gmail%' or not like '%yahoo%'
then things start to fail.
Before I start to integrate the nested select code in filter, I cannot get the multiple where field not like X or field1 not like Y working.
Any input is greatly appreciated.
sample data
name email
bob bob#gmail.com
joey joey#cisco.com
desired output
joey#cisco.com
UPDATE: Thank you all for your help. Answer to phase I of the question was to change from OR to AND. :)
Phase II: Instead of having a query that is larger and larger,.. I would rather use a query determine the items to exclude (meaning if any of them match, then exclude them).. so I would then add yahoo gmail protonmail to records in the code field of the filters table.. with that would it be
select distinct email from contacts where email not like in (select code from filters)
This fails as it says that the select has multiple records
UPDATE:
SELECT DISTINCT email FROM Contacts WHERE email NOT LIKE (select filters.code from filters where filters.id=4)
works.. but is only pulling one record as the filter. not all of them as filters.
You just need to use AND instead of OR.
SELECT distinct email
FROM
contacts
WHERE
email not like '%gmail%'
AND email not like '%yahoo%'
You can benefit from CHARINDEX like below, I think this will increase the performance of your query. Also, you can use group by instead of distinct, it will also help the performance.
select email
from contacts
where charindex('gmail',email) < 1
and charindex('yahoo',email) < 1
group by email
Two issue
you need the column name for each condition so add email after the OR
select distinct email from contacts where email not like '%gmail%' or email not like '%yahoo%'
and could be you want check for bot in the same time so you need AND
select distinct email from contacts where email not like '%gmail%' AND email not like '%yahoo%'
As others have noted, the correct boolean connector with NOT LIKE is AND, not OR.
You might see the logic using NOT:
select distinct email
from contacts
where not (email like '%gmail%' or email like '%yahoo%');
If your select has two NOT LIKE criteria connected by an OR condition then everything will meet the criteria. In this situation "gmail" is not like "yahoo" and "yahoo" is not like "gmail" so even those two will pass the criteria. By converting the select to use the AND condition instead you capture those situations. The syntax requires you to provide the field name in both conditions. I feel that this code is easy to read and meets your needs.
SELECT distinct email
FROM contacts
WHERE email not like '%gmail%'
AND email not like '%yahoo%'
Related
I have a scenario where authentication is done by the 3rd party and we store the records in our database ie. postgreSQL.
For Example:
email_id
details
name
aaa124#domain.com
some details
aaa124
aaa124#ex.domain.com
some details
aaa124
What I want is to extract all the recores by email Id only irrespective of the minor differences in the domain name changes. As they treat domain.com and ex.domain.com as same.
I have tried
SELECT * FROM table where (
email_id like 'aaa124%'
and
email_id like '%domain.com'
);
but looking for some optimal solution or regex etc.
Note : A user can be registered with multiple domains as well. so need to filter by domain also.
Thanks in advance.
You can combine LIKE clauses, like this:
select * from testing
WHERE email_id LIKE 'aaa124#%domain.com';
Output:
aaa124#domain.com
aaa124#ex.domain.com
Here is a db <> fiddle in action.
Do you want split_part()?
select split_part(email, '#', 1) as email_name,
split_part(email, '#', 2) as domain
from t;
Something like
select * from yourTable where email like 'aaa124#%';
This will select all users with the email aaa124 for all domains. You may want to use ilike instead of like if you also want match different cases of the email address.
I need the oracle query to retrieve users who has #gmail extension mails from email column from users table.
select * from users where email like '%#gmail%'
Use LOWER (or UPPER) to ensure that you match case.
Don't put a wild card at the end of the LIKE match as otherwise you will match valid e-mails such as myaddress#gmail.com.example.com.
GMail e-mails can use the gmail.com and googlemail.com domains interchangably; you may need to match both.
Like:
SELECT *
FROM users
WHERE LOWER( email ) LIKE '%#gmail.com'
OR LOWER( email ) LIKE '%#googlemail.com'
I have a question: Why can't I just use the following SQL query to get a list of unique eMail addresses from the PERSON table?
SELECT NOT DISTINCT Email FROM PERSON
I think the easiest and common way to achieve this is with grouping by the Email column and then keep the records having count = 1.
SELECT Email, COUNT(Email)
FROM PERSON
GROUP BY Email
HAVING COUNT(Email) > 1;
NOT DISTINCT is not working because it is not a valid expression.
DISTINCT is used to return only different values, so NOT before it is not working as you expect.
You asked to get a list of unique eMail addresses, which is done by:
SELECT DISTINCT(Email) FROM PERSON;
Standard SQL does not have NOT DISTINCT or anything like that.
I'm writing an application that implements a message system through a 'memos' table in a database. The table has several fields that look like this:
id, date_sent, subject, senderid, recipients,message, status
When someone sends a new memo, it will be entered into the memos table. A memo can be sent to multiple people at the same time and the recipients userid's will be inserted into the 'recipients' field as comma separated values.
It would seem that an SQL query like this would work to see if a specific userid is included in a memo:
SELECT * FROM memos WHERE recipients LIKE %15%
But I'm not sure this is the right solution. If I use the SQL statement above, won't that return everything that "contains" 15? For example, using the above statement, user 15, 1550, 1564, 2015, would all be included in the result set (and those users might not actually be on the recipient list).
What is the best way to resolve this so that ONLY the user 15 is pulled in if they are in the recipient field instead of everything containing a 15? Am I misunderstanding the LIKE statement?
I think you would be better off having your recipients as a child table of the memos table. So your memo's table has a memo ID which is referenced by the child table as
MemoRecipients
-----
MemoRecipientId INT PRIMARY KEY, IDENTITY,
MemoId INT FK to memos NOT NULL
UserId INT NOT NULL
for querying specific memos from a user you would do something like
SELECT *
FROM MEMOS m
INNER JOIN memoRecipients mr on m.Id = mr.memoId
WHERE userId = 15
No, you aren't misunderstood, that's how LIKE works.. But to achieve what you want, it would be better not to combine the recipients into 1 field. Instead try to create separate table that saves the recipient list for each memo..
For me I will use below schema, for your need:
Table_Memo
id, date_sent, subject, senderid, message, status
Table_Recipient
id_memo FK Table_Memo(id), recipient
By doing so, if you want to get specific recipients from a memo, you can do such query:
SELECT a.* FROM Table_Memo a, Table_Recipient b
WHERE a.id = "memo_id" AND a.id = b.id_memo AND b.recipient LIKE %15%
I am not sure how your application is exactly pulling these messages, but I imagine that better way would be creating a table message_recepient, which will represent many-to-many relationship between recipients and memos
id, memoId, recepientId
Then your application could pull messages like this
SELECT m.*
FROM memos m inner join message_recepient mr on m.id = mr.memoId
WHERE recepientId = 15
This way you will get messages for the specific user. Again, don't know what your status field is for but if this is for new/read/unread, you could add in your where
and m.status = 'new'
Order by date_set desc
This way you could just accumulate messages, those that are new
I have a simple table with just name and email called name_email.
I am trying to fetch data out of it so that:
If two rows have the same name, but one has an email which is ending with ‘#yahoo.com’ and the other has a different email, then the one with the ‘#yahoo.com’ email should be discarded.
what would be best way to get this data out?
Okay, I'm not going to get involved in yet another fight with those who say I shouldn't advocate database schema changes (yes, you know who you are :-), but here's how I'd do it.
1/ If you absolutely cannot change the schema, I would solve it with code (either real honest-to-goodness procedural code outside the database or as a stored procedure in whatever language your DBMS permits).
This would check the database for a non-yahoo name and return it, if there. If not there, it would attempt to return the yahoo name. If neither are there, it would return an empty data set.
2/ If you can change the schema and you want an SQL query to do the work, here's how I'd do it. Create a separate column in your table called CLASS which is expected to be set to 0 for non-yahoo addresses and 1 for yahoo addresses.
Create insert/update triggers to examine each addition or change of a row, setting the CLASS based on the email address (what it ends in). This guarantees that CLASS will always be set correctly.
When you query your table, order it by name and class, and only select the first row. This will give you the email address in the following preference: non-yahoo, yahoo, empty dataset.
Something like:
select name, email
from tbl
where name = '[name]'
order by name, class
fetch first row only;
If your DBMS doesn't have an equivalent to the DB2 "fetch first row only" clause, you'll probably still need to write code to only process one record.
If you want to process all names but only the specific desired email for that name, a program such as this will suffice (my views on trying to use a relational algebra such as SQL in a procedural way are pretty brutal, so I won't inflict them on you here):
# Get entire table contents sorted in name/class order.
resultSet = execQuery "select name, email from tbl order by name, class"
# Ensure different on first row
lastName = resultSet.value["name"] + "X"
# Process every single row returned.
while not resultSet.endOfFile:
# Only process the first in each name group (lower classes are ignored).
if resultSet.value["name"] != lastName:
processRow resultSet.value["name"] resultSet.value["email"]
# Store the last name so we can detect next name group.
lastName = resultSet.value["name"]
select ne.*
from name_email ne
where ne.email not like '%#yahoo.com' escape '\' or
not exists(
select 1 from name_email
where name = ne.name and
email not like '%#yahoo.com' escape '\'
)
You could use something like the following to exclude invalid email addresses:
SELECT name, email
FROM name_email
WHERE email NOT LIKE '%#yahoo.com' // % symbol is a wildcard so joe#yahoo.com and guy#yahoo.com both match this query.
AND name = 'Joe Guy';
Or do it like this to include only the valid email address or domain:
SELECT name, email
FROM name_email
WHERE email LIKE '%#gmail.com'
AND name = 'Joe Guy';
This works well if you know ahead of time what specific names you are querying for and what email addresses or domains you want to exclude or include.
Or if you don't care which email address you return but only want to return one, you could use something like this:
SELECT DISTINCT (name, email)
FROM name_email;
You could do
SELECT TOP 1 email
FROM name_email
WHERE name = 'Joe Guy'
ORDER BY case when email like '%yahoo.com' then 1 else 0 end
So sort them by *#yahoo.com last and anything else first, and take the first one.
EDIT: sorry, misread the question - you want a list of each name, with only one email, and a preference for non-yahoo emails. Probably can use the above along with a group by, I'll have to rethink it.
Grabbing all the rows from the database, knowing not what the names are (and not needing to care about that really), but just want them to show, and if matching, skip a match if the email contains, in this case, #yahoo.com
SELECT DISTINCT name, email FROM name_email
WHERE email NOT LIKE '%#yahoo.com'
GROUP BY name;
Doing that will grab all the rows, but only one of a record if the names match with another row. But then, if there are two rows with matching names, junk the one with #yahoo.com in the email.
Not very pretty, but I believe it should work
select
ne.name
,ne.email
from
name_email ne
inner join (
select
name
,count(*) as emails_per_name
from
name_email
group by name
) nec
on ne.name = nec.name
where
nec.emails_per_name = 1
or (nec.emails_per_name > 1 and ne.email not like ('%#yahoo.com'))
That is assuming that the duplicate emails would be in yahoo.com domain - as specified in your question, and those would be excluded if there is more than one email per name
If you are working with SQL Server 2005 or Oracle, you can easily solve your problem with a ranking (analytical) function.
select a.name, a.name_email
from (select name, name_email,
row_number() over (partition by name
order by case
when name_email like '%#yahoo.com' then 1
when name_email like '%#gmail.com' then 1
when ... (other 'generic' email) then 1
else 0
end) as rn) as a
where a.rn = 1
By assigning different values to the various generic email names you can even have 'preferences'. As it is written here, if you have both a yahoo and a gmail address, you can't predict which one will be picked up.
You could use a UNION for this. Select everything without the yahoo.com and then just select the records that have yahoo.com and is not in the first list.
SELECT DISTINCT (name, name_email) FROM TABLE
WHERE name_email NOT '%yahoo.com'
UNION
SELECT DISTINCT (name, name_email) FROM TABLE
WHERE name NOT IN (SELECT DISTINCT (name, name_email) FROM TABLE
WHERE name_email NOT '%yahoo.com')