2. Retrieving Data from Database How to retrieve data from the given database? After creating the database structure, customizing it to fit the needs and feeding it with data, the next step is to retrieve required data for performing various operations. So how do we get these data? The answer: Just like in English language, Microsoft SQL Server also provides us the basic keyword for retrieval of data called “Select” SELECT
3. Select Syntax The Syntax of the select statement is simple: The basic syntax for this DML ( Data manipulation Language) command is select <fieldName1, fieldName2,…> from <table name>; This will select the appropriate columns for the given table. As it is a DML command, it is not necessary to use the keyword TABLE(,as in ‘alter table’)
4. Displaying the entire table What if it is needed to display all the columns? The Syntax is: select * from tablename; ‘*’, the most widely used wildcard comes to our aid. Isn’t it much better than remembering all the column names. Example: select * from student; displays the entire student table
5.
6. likeselect * from tablename where <conditions>; select * from tablename where fieldNamelike <conditions>;
7.
8. For string matching, use the ‘like’ keyword. Here, wild card characters(% and _)% -character represents a group(or single) of characters _ -character represents a single character Illustration: To Update cartoons whose names start with the letter ‘a’ must be given as Update cartoon set rating=100 where cartoonName = ‘a%’
9. LIKE explained Illustration: To Update cartoons whose names start with the letter ‘a’ and the name must of 3 characters in length: Update cartoon set rating=100 where cartoonName = ‘a__’
10. Filter-out duplicate selections Now, we have a problem. What if there are two records have the same data? The select command will select both the records. To avoid this the distinct keyword is used. select distinct <col> from tablename; Note: Use distinct only for a single column.
11. Grouping of records In SQL, it is possible to group records based on the values of a particular field. Syntax: Select * from <tableName> group by <fieldName>; Example: To display the details of students, grouped based on their class, the command will be: Select * from student group by class;
12. Ordering of records In SQL, it is possible to sort records based on the values of a particular field. Syntax: Select * from <tableName> order by <fieldName>; Example: To display the details of students, sorted based on their GPAs, the command will be: Select * from student order bygpa; The default ordering is ascending in nature. To make it into descending, use the desc keyword. Eg: Select * from student order bygpadesc;