简体   繁体   中英

Wildcards in sql

How does wildcards works in sql. If I do select * from table it give all the fields. But if I do select a* from table it gives error. Shouldn't it give all fields which begins with a? I am little confused.

SELECT * FROM tableName literally means "select all columns from tableName".

Philip Graham is right about his answer where he asked to use a.*

Wildcards help you search for strings about which you are not sure. These are almost always used with the LIKE keyword and put in WHERE clauses or searched CASE statements.

There are two wildcard characters - % and _ .

% is used to find any string of 0 or more length. Eg,

SELECT firstName
  FROM persons
 WHERE UPPER(firstName) LIKE 'J%'

This will return all the firstName from the persons table where firstname starts with letter J . This would return "Jason", "James", "Josh", "Jessica" and much more.

Note that UPPER function was used to eliminate case sensitivity.

Next, you can have an _ character that looks for the presence of one single character.

SELECT firstName
  FROM persons
 WHERE UPPER(firstName) LIKE 'J_M__'

This would return "James", "Jimmy", "Jamos", "Jxmx" and filter away any "Jason", "Jaguar", etc.

For more info click here

You can use a.* where a is the name of the table. For instance in

select a.* from a left join b on a.id = b.id 

You would return only the fields from a but not from b

If want to use a wild card in SQL, You need to key on the column that you want to filter using LIKE .

SELECT * 
FROM table
WHERE column_name LIKE 'a%';

This will give you everything that begins with 'a' on that column.

If you don't want all the columns, you must explicitly give the name of each column that you want in the query.

SELECT LastName, FirstName, Address 
FROM table

So if you want all the fields that begin with 'a' you must name all the fields that begin with 'a' in the SELECT statement.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM