The SELECT statement is used to look for data, or to consult our tables.
The syntax for SELECT statement is:
Select*fromtable_name;
Example 1
Tip: The asterisk (*) is a quick way of selecting all columns!
SQLselect * from test;
ID NAME EMAIL
--------------------------------------------
1 Mike [email protected]
2 Dennis [email protected]
3 Jon jon2hotmail.com
Or you can restrict the search by calling the rows you chose
Example 2
SQLselect id , name from test;
ID NAME
------------------------------
1 mike
2 Dennis
3 Jon
SELECT using condition/s
Sintax:
Tip: The (--) is a quick way of commenting a line !
SELECT
FROM table_name WHERE
;
Example:
SQLselect Name --attribute name
from test--table name
where id=1;--condition
NAME
--------------------
mike
Also is important to mention that when the values that will be used in the conditions a string we must place it in single quotes.
Integer values do not require single quotes.
Example:
SQLselect email from test where name='mike';
EMAIL
--------------------[email protected]
Conditional selections used in the where clause:
= Equal
It will bring all the names that have the id equal to 1.
SQLSelect name from test where id=1;
NAME
--------------------
mike
Greater than
It will bring all the names that have the id bigger then 1.
SQLSelect name from test where id1;
NAME
--------------------
DennisJon
< Less than
It will bring all the names that have the id smaller then 2.
SQLSelect name from test where id=2;
NAME
--------------------
Mike
= Greater than or equal
SQLSelect name from test where id=2;
NAME
--------------------
Dennis
Jon
<= Less than or equal
SQLSelect name from test where id<=2;
NAME
--------------------
mike
Dennis
< Not equal to
SQLSelect name from test where id<2;
NAME
--------------------
mike
Jon
LIKE
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.
SQLSelect name from test where name like '%ke';
NAME
--------------------
mike
Notice that the select returned all the names that end up in 'ke' , knowing that '%' sign replaced the rest of the string.
We can use the '%' wildcard as well at the end :
Example:
SQLSelect name from test where name like 'mi%';
NAME
--------------------
Mike
At the beginning and at the end.
Example:
SQLselect name from test where name like '%i%';
NAME
-------------------
mike
Dennis
See that the select returned all the names that have letter 'i' inside.
Remember that we can use more then one character between the wildcard operators.
Example:
SQLSelect name from test where name like '%ik%';
NAME--------------------
Mike
We will learn more about the power of select after we go thrum the basics of Sql first.