Databse 2. SQL basic

SQL basic

Database Reminder

SQL Queries

  • SQL Queries are how we get information from a relational database
  • Start with SELECT command
  • E.g. SELECT name FROM Student;

Structure of a Query

  • basic form of a query:
    SELECT column_name FROM table_name WHERE condition_is_true;
  • SELECT * ----> returns complete rows

Examples

  • E.g. SELECT* FROM Lecturer
    SELECT* FROM Student
  • E.g. SELECT fname,sname,address FROM Student WHERE fname = 'Sally';
  • E.g. SELECT staffID FROM Lecturer WHERE school = 'Computing Science';
  • E.g. SELECT* FROM Student WHERE fname = 'Sally';

SQL Case Sensitivity

  • SELECT* FROM Student
  • SQL commands are not case sensitive
  • Convention is :
    -- SQL commends are in capitals(e.g. SELECT, FROM)
    -- Table names start with a capital letter (e.g.Student)
    -- Column names are in lower case (e.g. name, gender)

SELECT DISTINCT

  • get only distinct column values(delete the repeat results, or something dupicate)
  • SELECT DISTINCT fname FROM People;

Operators

Databse 2. SQL basic_第1张图片
image.png
IN and BETWEEN
  • IN: list possible values:
    SELECT name FROM Student WHEREstudentID IN(1,3,7);
  • BETWEEN: between an inclusive range
    SELECT name FROM Student WHERE studentID BETWEEN 1 AND 20;
  • NOT IN and NOT BETWEEN: similar as above
IS NULL
  • NULL values represent missing data, it's different from an empty string or 0
  • can use IS NULL and IS NOT NULL in queries
AND and OR
  • AND means all conditions must be true
  • OR means just one of the conditions must be true
  • e.g. SELECT studentID FROM Student WHERE fname='Sally' AND address='12 Hope Street';
  • e.g. SELECT studentID FROM Student WHERE fname='Sally' OR fname= 'Lindsey'
ORDER BY
  • order reuslts
  • e.g. SELECT coulumn_name,column_name FROM talbe_name ORDER BY column_name ASC|DESC;
  • ASC is defult
Functions
  • functions can be used for calculating the data
  • Syntax : SLECT function(column) FROM Table_name;
  • e.g. SELECT AVG(salary) FROM Lecturer;
  • useful aggregate functions:
  • AVG()
  • MAX()
  • MIN()
  • SUM()
  • COUNT()
COUNT()
  • SELECT COUNT(*) FROM Employee;
  • SELECT COUNT(salary) FROM Employee;
  • SELECT COUNT(DISTINCT salary) FROM Employee;
  • SELECT COUNT(staffID) FROM Lecturer WHERE school='Philosophy';

GROUP BY

  • returens values for distinct groups
  • e.g. SELECT COUNT(staffID), school FROM Lecturer GROUP BY school;----------> returns the number of lecturers in each school, one row for each distinct school

LIMIT

  • want a specific number of row back
  • e.g. SELECT fname, sname FROM Student WHERE sname< 'Black' LIMIT 10;

SQL Resources

  • postgresql tutorial

你可能感兴趣的:(Databse 2. SQL basic)