Advertisement
Guest User

Untitled

a guest
Oct 21st, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. -- sqlite
  2. .tables
  3.  
  4. -- mysql
  5.  
  6. -- psql
  7. \c students -- connect to student db
  8. \d -- shows all tables
  9. \d foo -- shows info about foo table
  10. \i tables.sql -- import and run entire file
  11.  
  12. -- -------- CREATION --------------
  13. CREATE DATABASE school;
  14. DROP DATABASE school;
  15.  
  16. -- Create table
  17. CREATE TABLE Students (
  18. -- colname TYPE OPTIONS
  19. id SERIAL PRIMARY KEY, -- autoincrementing integer
  20. fname VARCHAR(50),
  21. lname VARCHAR(50),
  22. dob DATE,
  23. -- constraints
  24. );
  25.  
  26. CREATE TABLE Address (
  27. id SERIAL PRIMARY KEY,
  28. street VARCHAR(50),
  29. city VARCHAR(50),
  30. state CHAR(2),
  31. zip CHAR(5)
  32. );
  33.  
  34. CREATE TABLE StudentAddressess (
  35. student_id INTEGER REFERENCES Students (id), -- Foreign Key
  36. addr_id INTEGER REFERENCES Addresses (id),
  37. active BOOLEAN;
  38. PRIMARY KEY (student_id, addr_id) -- Composite primary key
  39. );
  40.  
  41.  
  42. INSERT INTO students (name, ssn, dob) VALUES ('bob', '123456789', '01-01-1999');
  43.  
  44. UPDATE students SET name = 'tom', dob = '01-02-1999';
  45.  
  46. UPDATE students
  47. SET name = 'tom', dob = '01-02-1999'
  48. WHERE id = 12;
  49.  
  50. -- Delete a student
  51. DELETE FROM students
  52. WHERE id = 12;
  53.  
  54. -- Kill the table entirely
  55. DROP TABLE students;
  56.  
  57. -- -------- QUERIES --------------
  58.  
  59. -- JOINS
  60.  
  61.  
  62. -- Self join
  63.  
  64. CREATE TABLE Residences (
  65. student_id REFERENCES Students (id),
  66. building VARCHAR(50),
  67. room VARCHAR(20),
  68. );
  69.  
  70. -- Create a list of roomates. Watch for dupes
  71. Select a.student_id, b.student_id, a.building, a.room
  72. FROM Residences a, Residences b
  73. WHERE
  74. a.building = b.building AND
  75. a.room = b.room AND
  76. a.student_id < b.student_id -- avoid dupes and same id
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement