Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select particular range of values in MySQL table?

Tags:

sql

select

mysql

The following is my MySQL table. I want to select a particular range of values from my table hello.

name      age        job       gender

A         33         dgfd      m
b         44         gdfg      f
c         21         jhkh      m
e         23         etertr    m

How would I select a male whose age falls into the age category of 20-30 years.

SELECT hello.*
WHERE hello.age='20-30' AND hello.gender='m';
like image 382
Ameer Avatar asked Mar 22 '13 15:03

Ameer


2 Answers

You can use a WHERE clause to filter the data:

select name, age, job, gender
from hello
where age >=20
  and age <=30
  and gender = 'm'

See SQL Fiddle with Demo

This can also be written using BETWEEN:

select name, age, job, gender
from hello
where age between 20 and 30
  and gender = 'm'

See SQL Fiddle with Demo.

Typically you will want to store a date of birth instead of the age of a person, then the age can be calculated when needed.

like image 100
Taryn Avatar answered Nov 14 '22 00:11

Taryn


SELECT name
FROM hello
WHERE age BETWEEN 20 AND 30
  AND gender = 'm'

Don't store age. Store a date field and calculate the age. What would happen if the person got older?

like image 36
Kermit Avatar answered Nov 13 '22 23:11

Kermit