Advertisement
beccafuchs

SQL snippets creating, reading and writing to tables

May 17th, 2019
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.55 KB | None | 0 0
  1. --SQL script for creating, reading and writing tables in SQLite database
  2.  
  3. --creating the tables 'author' and 'project' (database first)
  4. CREATE TABLE IF NOT EXISTS "Author" (
  5.   "author_id" INTEGER PRIMARY KEY AUTOINCREMENT,
  6.   "first_name" VARCHAR(30) NOT NULL,
  7.   "last_name" VARCHAR(50) NOT NULL,
  8.   "middle_names" VARCHAR(100) NOT NULL,
  9.   "pseudonym" VARCHAR(100) UNIQUE,
  10.   "contact" VARCHAR(100) NOT NULL
  11. );
  12.  
  13. CREATE TABLE IF NOT EXISTS "Project" (
  14.   "project_id" INTEGER PRIMARY KEY AUTOINCREMENT,
  15.   "author_id" INTEGER NOT NULL REFERENCES "Author" ("author_id") ON DELETE CASCADE,
  16.   "title" VARCHAR(200) UNIQUE NOT NULL,
  17.   "genre" VARCHAR(50) NOT NULL,
  18.   "description" TEXT NOT NULL,
  19.   "creation_time" DATETIME NOT NULL,
  20.   "change_time" DATETIME NOT NULL,
  21.   "deleted" INTEGER NOT NULL
  22. );
  23.  
  24. CREATE INDEX "idx_project__author_id" ON "Project" ("author_id");
  25.  
  26. -- inserting new entry in table 'author'
  27. INSERT INTO author(
  28.     first_name,
  29.     middle_names,
  30.     last_name
  31. )
  32. VALUES(
  33.     "Johann",
  34.     "Wolfgang",
  35.     "von Goethe"
  36. );
  37.  
  38. #retrieving the entry WITH LAST name 'von Goethe' FROM TABLE 'author'
  39. SELECT *
  40. FROM author
  41. WHERE author.last_name = "von Goethe";
  42.  
  43. #select ALL projects BY Goethe
  44. SELECT *
  45. FROM project
  46. INNER JOIN author
  47. ON (author.author_id = project.author_id)
  48. ORDER BY (project.title);
  49.  
  50. #update Goethes LAST name AND remove the 'von'
  51. UPDATE author
  52. SET last_name = "Goethe"
  53. WHERE last_name = "von Goethe";
  54.  
  55. #delete Goethe FROM author TABLE
  56. DELETE FROM author
  57. WHERE first_name = "Johann" AND middle_names = "Wolfgang" AND last_name = "Goethe"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement