|=--------------------------------------------------=| _________________ .____ ___________________ / _____/\_____ \ | | \_ _____/\______ \ \_____ \ / / \ \| | | __)_ | | \ / \/ \_/. \ |___ | \ | ` \ /_______ /\_____\ \_/_______ \/_______ //_______ / \/ \__> \/ \/ \/ |=--------------------------------------------------=| . |03.04 - Querying the data I. . |=--------------------------------------------------=| In previous chapters we created a table. We inserted data into it. This time we will construct a query to retrieve data from it. Let's begin with retrieval of all data presented in the table: select * from users; This will give us following result: user_key user_name user_password ---------- ----------- --------------- 1 user1 pass 2 user2 pass 3 user3 pass 4 user4 pass Let's examine the query. SELECT is a keyword. Then there is star *. The star is issued when we want to select all the columns from the table. Then there is a FROM keyword specified. And the last word is the table name (users). Next we will try to select only certain columns from the user table but still all rows: select user_name from users; give us: user_name ----------- user1 user2 user3 user4 The database returns only 1 column (user_name) but still all the rows. What if we would like to limit the result of the query to only one row and e.g. two columns? We would provide following query: select user_key, user_name from users where user_key = 1; The result of the query would be following: user_key user_name ---------- ----------- 1 user1 In the above SELECT query we added the WHERE keyword. After this keyword we need to specify filter clause to tell the database what rows it has to return to us. WHERE is the filter keyword. And then in the expression user_key = 1 we specify selection of only 1 row (because we have user_key as unique primary key) and limit the results to the row where user_key equals 1. Let's say we would like to explore the user's list and search for the users where theirs username contains certain string. This could be achieved by the LIKE clause: select user_key, user_name from users where user_name like '%2'; The result would be: user_key user_name ---------- ----------- 2 user2 What we have specified here is the LIKE keyword and specified the filter to '%2'. That would read as search for rows where the user_name contains any string from the beginning but the last character is 2. The percentage sign (%) translates here to "any characters". In the next chapter we will query some more data. |=--------------------------------------------------=| ; v | Thanks Linux and Vim | buy me a coffee | o |; |=--------------------------------------------------=| |