How to check the substring in an SQL query?

advertisements

Here is my Weapons table:

Name / DPS / Style

Noxious Bow / 1000 / Range
Chaotic Staff / 800 / Magic
Armadyl Crossbow / 750 / Range
Saradomin Godsword / 600 / Melee
Dragon Battlestaff / 600 / Magic
Dragon Longsword / 550 / Melee
Elder Shortbow / 500 / Range
Darklight / 400 / Melee

Here is what I tried:

SELECT Name, DPS, Style
FROM Weapons
HAVING SUBSTRING(Name, 1, 1)='D';

I want all Weapons that start with the letter D to be displayed. However, this code is giving me a syntax error.


As you're using Oracle, the function is SUBSTR, not SUBSTRING, and for any RDBMS, you'd need to use WHERE, not HAVING:

SELECT Name, DPS, Style
FROM Weapons
WHERE SUBSTR(Name, 1, 1)='D';

SUBSTRING would have worked fine in Microsoft SQL Server.

Also, the LEFT function is quite widely supported, and might stand a better chance of using an index, if one is defined on Name. This will work in Oracle, SQL Server and others:

SELECT Name, DPS, Style
FROM Weapons
WHERE LEFT(Name, 1)='D';

However, the best option is probably using LIKE, which is widely-supported and flexible, and will also likely use an index on the Name column, if one exists, as long as the fixed text you're searching for is at the beginning:

SELECT Name, DPS, Style
FROM Weapons
WHERE Name LIKE 'D%';

You could probably do with going through a basic SQL tutorial at this stage, and bear in mind that while "SQL" has a standard core, each version is different and you'll need to look for Oracle-specific advice if you're using Oracle.