Difference between revisions of "Select Queries"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
Line 13: Line 13:
  
 
  <syntaxhighlight lang=sql>
 
  <syntaxhighlight lang=sql>
SELECT *
+
SELECT *
FROM  Book
+
FROM  Book
WHERE price > 100.00
+
WHERE price > 100.00
ORDER BY title;
+
ORDER BY title;
 
  </syntaxhighlight>
 
  </syntaxhighlight>
  
Line 22: Line 22:
  
 
==Relational Databases & Select==
 
==Relational Databases & Select==
using a relational database (two or more related tables) makes the select statement more complex because you can obviously select data from multiple tables and also use criteria on multiple tables in the where section. So:
 
#Any field name which causes ambiguity must also have the table specified, ie table.fieldname
 
#The from section must include the tables for every field in the where or select sections
 
#The where section must contain the criteria to explain how the tables in the from section are related
 
  
so for example:
+
<syntaxhighlight lang=sql>
 
+
SELECT TutorGroup.Name, Student.Name
:*this should be primary key to foreign key, so if you have just 2 tables - table1.primary = table2.foreign
+
FROM  TutorGroup, Student
:* 3 tables would have something like table1.primary = table2.foreign AND table1.primary = table3.foreign
+
WHERE Student.ID = TutorGroup.StudentID
 
+
AND Student.YearGroup = 12 AND Student.Gender = 'Male'
Remember this is on top of the criteria you need to use for the question or output required.
+
ORDER BY TutorGroup.Name;
 +
</syntaxhighlight>

Revision as of 14:16, 17 December 2016

  • Used for fetching information from an SQL database.
  • 'Outputs' the data once successfully selected
  • Allows selection from multiple tables but not multiple databases.

The Basic Construct

  SELECT `data` FROM `TABLE`
  WHERE `Condtion`
  ORDER BY `TABLE` ASC / DESC ;

Basic Example

 SELECT *
 FROM  Book
 WHERE price > 100.00
 ORDER BY title;

Remember the select can have * to select all fields, however questions will normally specify what fields to select. The from section should identify which table(s) to select the data from. The where section should include the criteria used to select the data, this could be a simple statement as above but remember you can also include other operators such as and, or, not, like, and so on.

Relational Databases & Select

 SELECT TutorGroup.Name, Student.Name
 FROM  TutorGroup, Student
 WHERE Student.ID = TutorGroup.StudentID
 AND Student.YearGroup = 12 AND Student.Gender = 'Male'
 ORDER BY TutorGroup.Name;