Inserting and Selecting Data

DESCRIBE / DESC Command

  • Purpose: display the structure (schema) of an existing table so the developer knows how to write valid queries and DML statements.
    • Syntax (case-insensitive):
    • DESCRIBE tablename;DESCRIBE\ tablename; or DESC tablename;DESC\ tablename;
    • Columns returned in result grid:
    • Field – column name.
    • Type – data type (e.g., varchar(40)varchar(40), decimal(10,2)decimal(10,2), datedate …).
    • Null – indicates whether the column may contain NULLNULL (YES/NO).
    • Key – shows if the column is part of a key (PRI, UNI, MUL).
    • Default – default value automatically inserted when no explicit value is given.
    • Extra – additional metadata (e.g., auto_increment).
  • Practical workflow in MySQL Workbench (illustrated in screenshot):
    • Selecting a schema → Right-click table → Table Inspector → Columns OR run DESCagent;DESC agent; in SQL editor.
    • Output shows e.g.
    • agentcodeagent_code varchar(6)NOT NULLPRIMARY KEYvarchar(6) NOT\ NULL PRIMARY\ KEY
    • commissioncommission decimal(10,2)NULLdecimal(10,2) NULL
    • Message pane confirms "6 row(s) returned" and execution time.
  • Significance:
    • Essential before INSERTs or UPDATEs to avoid type & constraint violations.
    • Helps detect “NOT NULL” columns that must always receive a value.

Data Manipulation Language (DML) & Transactions

  • Core DML commands:
    • SELECTSELECT – read data (does not modify); always immediately visible to every user.
    • INSERTINSERT, UPDATEUPDATE, DELETEDELETE – modify data; changes stay private to current session until committed.
  • Atomicity & Isolation (ACID):
    • Other sessions can’t see uncommitted changes; guarantees consistency or total rollback.

Basic INSERT Statement

  • Complete‐value form (column list omitted because all columns filled, in table-defined order):
    • INSERTINTOpatientVALUES(232,Mohammed,AlWalkra,44311132);INSERT INTO patient VALUES (232,'Mohammed','Al Walkra','4431-1132');
    • Additional examples supplied for patient IDs 334334 and 400400.
  • Multi-row insert (MySQL-specific; Oracle requires separate statements or INSERTALLINSERT ALL):
    • INSERTINTOpatientVALUES (401,Next,Subject,12344321), (402,Final,Demo,44443333);INSERT INTO patient VALUES\ (401,'Next','Subject','1234-4321'),\ (402,'Final','Demo','4444-3333');
    • Benefits: fewer round-trips, faster bulk loading.

Handling Missing Values During INSERT

  • Provide explicit column list whenever you omit one or more attributes:
    • INSERTINTOpatient (patientid,name) VALUES(500,Ali);INSERT INTO patient\ (patient_id, name)\ VALUES (500,'Ali');
  • Rules:
    • You may reorder columns in the list to match your data sequence.
    • Columns declared NOT NULLNOT\ NULL (without a default) must receive a value, otherwise DB rejects statement.
    • Columns that are nullable receive NULLNULL automatically unless a DEFAULT is defined.

Transaction Control Language (TCL)

  • Default behaviour in a fresh MySQL install: autocommit = ON.
    • Each DML statement implicitly commits.
  • Disabling autocommit for group operations:
    • START TRANSACTION;START\ TRANSACTION; (alias BEGIN;BEGIN;) — begins an explicit transaction; Workbench UI also has a toggle button.
    • Perform multiple INSERT/UPDATE/DELETEINSERT/UPDATE/DELETE.
    • COMMIT;COMMIT; — persist all changes so other users can see them.
    • ROLLBACK;ROLLBACK; — revert to pre-transaction state.
    • Network loss / client crash behaves like an automatic rollback, safeguarding consistency.
  • All statements in the same transaction succeed or fail together, across multiple tables (atomicity guarantee).

SELECT Statement Fundamentals

  • Projection vs Selection:
    • Projection = choose columns. Example: SELECTdescription,priceFROMmedicine;SELECT description, price FROM medicine;
    • Selection = choose rows (via WHEREWHERE). Example: SELECT * FROM medicine WHERE price>150;
  • SELECTSELECT * returns every column (useful for ad-hoc debugging, discouraged in production for performance).
  • Sample output (first query above) illustrates descriptive text + price for each medicine record.

WHERE Clause & Conditional Selection

  • Numeric comparison operators: =,
  • Character string comparison obeys collation (case-insensitive by default in MySQL unless BINARY or explicit collations used).

Date-Time Comparisons & Arithmetic

  • Date literal format (MySQL default) YYYYMMDD'YYYY-MM-DD' or full timestamp YYYYMMDDHH:MI:SS'YYYY-MM-DD HH:MI:SS'.
  • Range selection:
    • SELECT * FROM appointment WHERE start_time>= '2022-09-08' AND start_time < '2022-09-09'; (grabs all on Sept 8).
  • Current date/time:
    • NOW();NOW(); returns current timestamp.
    • Example filter: SELECT * FROM appointment WHERE start_time< NOW(); (past appointments).
  • Adding intervals:
    • SELECTDATEADD(NOW(),INTERVAL5DAY);SELECT DATE_ADD(NOW(), INTERVAL 5 DAY); → date five days ahead; useful for reminders & expirations.

Logical Operators

  • Combine multiple predicates:
    • ANDAND (both true) – SELECT * FROM student WHERE name='Test' AND gpa<3;
    • OROR (either true) – SELECT * FROM student WHERE name='Test' OR gpa<3;
    • NOTNOT (negates) – SELECT * FROM student WHERE NOT (gpa>=3);
  • Operator precedence: NOTNOT > ANDAND > OROR (parentheses recommended for clarity).

Special Operators

  • BETWEENBETWEEN inclusive shortcut:
    • columnBETWEEN4AND10column BETWEEN 4 AND 10 ≡ column>=4\ AND\ column<=10.
  • IS NULLIS\ NULL / IS NOT NULLIS\ NOT\ NULL — only correct way to test tri-valued logic; column=NULLcolumn=NULL fails (unknown).
  • IN(.)IN (….) list membership; more readable than multiple ORORs.
    • Example: SELECTFROMstudentWHEREidIN(1234,1235,2222);SELECT * FROM student WHERE id IN (1234,1235,2222);

Pattern Matching with LIKE

  • Wildcard % matches 0+ characters.
    • m'm%' → starts with m.
    • '%m' → ends with m.
    • '%m%' → contains m anywhere.
  • MySQL also supports underscore _ for single-character wildcard.
  • Performance hint: leading wildcard (e.g., '%m') prevents index usage.

Real-World / Best-Practice Connections

  • DESCRIBE + column metadata informs ORMs/schema-driven applications for automatic validation.
  • Transactions critical in banking, inventory, healthcare (e.g., updating appointment & billing tables atomically).
  • Missing-value strategy must align with data governance; excessive NULLs can hamper analytics.
  • Pattern searches (LIKE) useful for end-user search boxes but often replaced by full-text indexes or external search engines for scalability.
  • Ethical dimension: When dealing with patient table examples, ensure compliance with HIPAA/GDPR; practice on anonymized data.

Practice & Further Learning Resources

  • Interactive SQL sandboxes (free):
    • W3Schools SQL editor: https://www.w3schools.com/sql/
    • W3Schools SQL quiz for quick recall.
    • GeeksforGeeks SQL tutorial + explanation-heavy articles.
    • PracticeTestGeeks: certification-style question bank.
  • Recommended videos (from slides):
    • Inserting data: https://www.youtube.com/watch?v=Cxilfg-M158
    • Transaction control: https://www.youtube.com/watch?v=GOQVlrQohtM
    • WHERE & logical operators: https://www.youtube.com/watch?v=kUDznltqKbl
    • Pattern matching: https://www.youtube.com/watch?v=T11d2ScMtk8

Quick Reference Cheat-Sheet (mini)

  • DESCRIBE table;
  • INSERT INTO t (c1,c2) VALUES (v1,v2);
  • START TRANSACTION; … COMMIT; / ROLLBACK;
  • SELECT col1 FROM t WHERE condition;
  • Date calc: DATE_ADD(date, INTERVAL n DAY);
  • Logical: AND / OR / NOT. Special: BETWEEN / IN / IS NULL / LIKE.