tags:

views:

100

answers:

4

I have a database table with a few thousand entries. A part of the entries (~20%) have been entered with a fully capitalized strings in the 'name' column.

Example:

id | name
---------
1 | THOMAS GOLDENBERG
2 | Henry Samuel
3 | GIL DOFT
4 | HARRY CRAFT
5 | Susan Etwall
6 | Carl Cooper

How would an SQL query look like that selects all entries with a fully capitalized string in the name column? (i.e. in the example: those with the ID 1,3,4)

+5  A: 

In MySQL it would be:

SELECT id FROM table WHERE name = UPPER(name);

I think this would work the same way in SQL Server, DB2 and Postgres.

Kaleb Brasee
Thank you very much. This also works with Apache Derby.
pruefsumme
At least in Microsoft SQL Server, you need to make sure that you have a collation which is case sensitive, otherwise each record will match your query.
Oliver Hanappi
I'm not aware of collation issues with Oracle, but UPPER is supported.
OMG Ponies
+2  A: 
select * from your_table where name = upper(name)
Pablo Santa Cruz
+4  A: 

What database system?

In theory you can do a simple SELECT ... WHERE name = UPPER(name); but that does not always work. Depending on the collation of your data, you may found that all records satisfy this condition because the comparison used may be case insensitive.

You need to ensure you compare using a case sensitive collation, and the correct answer depends on the database platform you use. For example, using SQL Server syntax:

SELECT ... WHERE Name COLLATE Latin1_General_100_CS_AS = UPPER(Name);

This also works in MySQL with the condition that you use a collation name valid on MySQL.

Remus Rusanu
+1  A: 

Here's a MySql function to convert uppercase to title case:

example:

update your_table set name = tcase(name) where name = upper(name);

function:

CREATE FUNCTION `tcase`(str text) RETURNS text CHARSET latin1
    DETERMINISTIC
BEGIN

  DECLARE result TEXT default '';
  DECLARE space INT default 0;
  DECLARE last_space INT default 0;

  IF (str IS NULL) THEN
    RETURN NULL;
  END IF;    

  IF (char_length(str) = 0) THEN
    RETURN '';
  END IF;

  SET result = upper(left(str,1));
  SET space = locate(' ', str);    

  WHILE space > 0 DO            
    SET result = CONCAT(result, SUBSTRING(str, last_space+2, space-last_space-1));            
    SET result = CONCAT(result, UPPER(SUBSTRING(str, space+1, 1)));        
    SET last_space = space;
    SET space = locate(' ', str, space+2);    
  END WHILE;

  SET result = CONCAT(result, SUBSTRING(str, last_space+2));

  RETURN result;

END $$    
DELIMITER ;
Michael Valenty