Sunday, 24 January 2016

How to select data in the SQL

Selecting Data

The select statement is used to query the database and retrieve selected data that match the criteria that you specify. Here is the format of a simple select statement:
select "column11"
  [,"column12",etc] 
  from "tablename"
  [where "condition"];
  [] = optional
The column names that follow the select keyword determine which columns will be returned in the results. You can select as many column names that you'd like, or you can use a "*" to select all columns.
The table name that follows the keyword from specifies the table that will be queried to retrieve the desired results.
The where clause (optional) specifies which data values or rows will be returned or displayed, based on the criteria described after the keyword where.
Conditional selections used in the where clause:
=Equal
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal
<>Not equal to
LIKE*See note below
The LIKE pattern matching operator can also be used in the conditional selection of the where clause. Like is a very powerful operator that allows you to select only rows that are "like" what you specify. The percent sign "%" can be used as a wild card to match any possible character that might appear before or after the characters specified.
 For example:
select first, last, city
   from empinfo
   where first LIKE 'Pu%';
This SQL statement will match any first names that start with 'Pu'. Strings must be in single quotes.
Or you can specify,
select first, last
   from empinfo
   where last LIKE '%d';
This statement will match any last names that end in a 'd'.
select * from empinfo
   where first = 'Pune';
This will only select rows where the first name equals 'Pune' exactly.

Sample Table: empinfo
first
last
id
age
city
state
John
sons
90901
45
Delhi
Delhi
Mary
coms
90902
25
Punjab
Punjab
Eric
wards
80801
32
Pune
Maharastra
Mary Com
Edwards
80802
32
hyderabad
Telangana
Ginger
well
90802
42
Chennai
Tamilanadu
Sebastian
Wala
98001
23
Goa
Goa
Gussa
Gray
20802
35
Banglore
Karnataka
Mary Com
May
30802
52
Mumbai
Maharastra
Erisca
Williams
32427
60
Noida
Haryana
Lebroy
Lable
34243
22
Luknow
UP
Emma
Clever
33343
22
Kolkata
Bengal


Try the below sample select statements at home.
select first, last, city from empinfo; 

select last, city, age from empinfo
       where age > 30; 

select first, last, city, state from empinfo
       where first LIKE 'S%'; 

select * from empinfo; 

select first, last, from empinfo
       where last LIKE '%s'; 

select first, last, age from empinfo
       where last LIKE '%ary%'; 

select * from empinfo where first = 'Erisc';

No comments:

Post a Comment