The below Postgres SQL query is returning all records available in the table. Can someone give explanation for this? . Also please let me know what * represents in case of postgres regular expression.
Employee table contains :
name
Chennai
Delhi
Hydrabad
NewYark
ABC
select * from employee where name ~ 'Z*'
This is the correct query for finding name starting with 'Z' :
SELECT record FROM myrecords WHERE name ~ '^Z';
in your query :
select * from employee where name ~ 'Z*'
the meaning is where the name matches ZERO or MORE sequences of character "Z", hence returning all records.
*
in the matching criteria means ZERO or MORE occurences.
*
along with tilda means case insensitive match ie ~* 'Z' will match both "z" and "Z"
For more have a look here :
http://oreilly.com/pub/a/databases/2006/02/02/postgresq_regexes.html?page=1
The *
quantifier means zero or more . Since every name contains at least zero Z
characters, every row is returned.
You don't need to use a regex to find strings starting with a character, you can just use LIKE
:
SELECT record FROM myrecords WHERE name LIKE 'Z%';
If you want names starting with Z using a regex , try this:
SELECT record FROM myrecords WHERE name ~ '^Z';
If you want names containing at least one Z, try one of these:
SELECT record FROM myrecords WHERE name LIKE '%Z%';
SELECT record FROM myrecords WHERE name ~ 'Z';
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.