Dreevoo.com | Online Learning and Knowledge Sharing
 
Home | Programs | Programming languages | PHP & MySQL | Learn to use select query in SQL
Guest
Click to view your profile
Topics
Programs
Languages
Recipes
Home
Shortcuts
 
 

Learn to use select query in SQL

Using SELECT SQL queries is the most common way to retrieve data from MySql and also most of other databases.

 
  Author: podtalje | Version: phpMyAdmin | 18th May 2013 |  
 
 
1.
 

For the purpose of our lesson we will use phpMyAdmin tool.

Basic usage of this tool is described in lesson where you will learn how to create a new database and tables.


 
 
2.
 

For sample data we will use table with name my_table which contains the following data:

id number text date
1 123 sample text 3.5.2013
2 22 New text 10.5.2013
3 1000 My description 10.5.2013
4 444 new text 10.5.2013
5 444 my text 10.5.2013

 
 
3.
 

Most common SQL command is SELECT.

Syntax:
SELECT field_name FROM tabele_name

If we want to get all number values from our table my_table, we execute the following query:
SELECT number FROM my_table

 
 
4.
 

In SELECT query we can also put more than one field name.

In case we want to also see date field, we use the following query:
SELECT number, date FROM my_table

 
 
5.
 

And if we want to get all the fields from our table, we can use * character.

Example:
SELECT * FROM my_table


 
 
6.
 

In practice we usually want to retrieve only data that meets certain criteria. In this case we use keyword WHERE.

Syntax:
SELECT field_name FROM table_name WHERE field_name condition

This is best shown on example. If we want to retrieve only records where value of number field is 444, we use:
SELECT number, text FROM my_table WHERE number='444'

 
 
7.
 

We can also specify more than one condition.

Example:
SELECT * FROM my_table WHERE number='444' OR date='2013-05-10'

Instead of OR operator we can also use AND.

 
 
8.
 

It is also possible to sort the data.
For this we use ORDER BY.

Syntax:
SELECT field_names FROM table_name WHERE condition ORDER BY field_name

So if we want to get all the data, sorted by number, we can use:
SELECT * from my_table ORDER BY number

 
 
9.
 

In practice we will usually use more than one table. Lucky for us this is very easy to do in SQL.

In the example below we will use additional table my_table2.
SELECT a.*, b.* FROM
my_table AS a, my_table2 AS b
WHERE a.id = b.id

In this case we have retrieved records from both tables where value of id field in first table is equal to the value of id field in second table.

 
 
 
   
  Please login to post a comment
   
 
 
online learning made for people
Dreevoo.com | CONTRIBUTE | FORUM | INFO