SQL SELECT where column CONTAINS substring - sql

I have a database containing all usernames. Now, I have a page where I can search for an user. At the moment I use the following SQL:
SELECT uid, username, id, status
FROM users
WHERE `username` LIKE <search string>
Now, I have a record with the username Hattorius. But when I use that SQL syntax, and search for hatt. It doesn't give any results. How can I still make this work?
I searched some around, but nobody really had an answer to this.

Try to use LIKE :
SELECT uid, username, id, status
FROM users
WHERE `username` LIKE '%hatt%'

Remove the single quotes:
SELECT uid, username, id, status
FROM users
WHERE username LIKE '%hatt%'

Related

Salesforce - Bind variables only allowed in Apex code - MALFORMED_QUERY

I need an equivalent SOQL query to this SQL query:
SQL query:
SELECT id, username, (SELECT username FROM users where id = u.manager_id) as manager_username
FROM users u
I have tried
SELECT Id, Username, (SELECT Username FROM User WHERE Id=usr.ManagerId) FROM User usr
What I keep getting is
[
{
"message": "\n(SELECT Username FROM User WHERE Id=usr.ManagerId) FROM User usr WHERE\n
^\nERROR at Row:1:Column:57\nBind variables only allowed in Apex code",
"errorCode": "MALFORMED_QUERY"
}
]
Any suggestions?
SOQL doesn't support field comparison. But in your case, it's not needed. The manager is the parent record, so its fields can be accessed via dot notation. Your query can just be:
SELECT Id, Username, Manager.Id, Manager.Username FROM User

Problems with joining two tables in SQL

I have two tables. user(user_id, username, password, age) and comment(comment_id, comment, user_id(foreign key)).
I'm trying to get username from user, using the user_id provided in comment.
My query looks like this:
$sql = "SELECT username FROM user WHERE user_id = (SELECT user_id FROM comments)";
I'm getting null. Is my brain working poorly or is it something else I messed up?
I just want to display all comments after each other, with the username before it.
Use IN instead of "=" .
SELECT username FROM user WHERE user_id IN (SELECT user_id FROM comments);
OR you can use a proper join, something like:
SELECT username FROM user,comments WHERE user.user_id = comments.user_id
That's not a join - a join would be:
$sql = "SELECT username FROM user u JOIN comments c ON u.user_id = c.user_id";
When you use a subquery with =, the subquery must return one value. To show all related records in a related table, use JOIN instead.

How to use LIKE and IN operators in one query?

My simple sql statement is this:
SELECT USERNAME FROM ALL_USERS;
But I want to filter system users from the result. I searched but couldn't find anything that Oracle provided; so I tried a statement like this and it doesn't work:
select username from all_users where username not like '%SH%'
or username not like '%SYS%'
or username not in ('ANONYMOUS',
'DBSNMP',
'MGMT_VIEW',
'ORDPLUGINS',
'OUTLN',
'SI_INFORMATION_SCHEMA',
'WK_TEST',
'WKPROXY',
'XDB');
This doesn't work. How should I modify my query for the desired output or maybe there is something oracle provides to get predefined system accounts?
A slight twist on the other answers: not (A or B or C) = not A and not B and not C, so what you probably originally wanted was:
select username from all_users
where not (username like '%SH%'
or username like '%SYS%'
or username in ('ANONYMOUS',
'DBSNMP',
'MGMT_VIEW',
'ORDPLUGINS',
'OUTLN',
'SI_INFORMATION_SCHEMA',
'WK_TEST',
'WKPROXY',
'XDB')
);
Instead of OR, you will need to use AND
select username from all_users where username not like '%SH%'
AND username not like '%SYS%'
AND username not in ('ANONYMOUS',
'DBSNMP',
'MGMT_VIEW',
'ORDPLUGINS',
'OUTLN',
'SI_INFORMATION_SCHEMA',
'WK_TEST',
'WKPROXY',
'XDB');
However, this will also filter legitimate non-system users whose names contain SYS or end in SH. User JOSH will be lost.
replace or with AND , I think it will start working.
However a better approach might be to have a flag indicating whether its a system user or not. A more sophosticated approach might be to have seperate table for rights that will have many to many relationship with User table.
You can try this:
select username from all_users where username not like '%SH%'
AND username not like '%SYS%'
INTERSECT
select username from all_users where username not in ('ANONYMOUS',
'DBSNMP',
'MGMT_VIEW',
'ORDPLUGINS',
'OUTLN',
'SI_INFORMATION_SCHEMA',
'WK_TEST',
'WKPROXY',
'XDB');

mysql query, two select

As soon as I apologize because I do not know or be able to explain exactly trouble.
How get value from table user_address.
how to pass user ID in the second "select".
select id, name, age,
(select address
from user_address
where user_id = ??user.id
ORDER BY address_name
LIMIT 1) AS address
from user
As an addendum to what already exists, you should probably not be relying on the specific order of rows in the database to give some sort of semantic meaning. If you have some better way of identifying which address you're after, you could use a join, such as:
select id, name, age, address
from user
inner join user_address
on user.id=user_address.user_id
where address_type='Home'
(adjust the where clause to whatever)
I assumed that you want to get something like the first address for a user
(each user may have a couple of addresses)
-there is another option that you want to find the first persone that lives in a given address (The solution below doesn't address this case)
SELECT u.id,u.name,u.age,a.ua as address
FROM
(
SELECT * FROM users
) u
INNER JOIN
(
SELECT userID, MIN(address) AS ua
FROM user_address
GROUP BY userID
) a
on u.id = a.userID
The syntax is for SQLServer - if you use MSAccess(you can use First and not min)
Hope it helps
Asaf

distinct sql query

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')