Basic SQL Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Basic SQL Structured Query Language (SQL): Considered one of the major reasons for the commercial success of relational databases 2 Basic SQL Terminology: Table, row, and column used for relational model terms relation, tuple, and attribute 3
The CREATE TABLE Command in SQL Specifying a new relation Provide name of table Specify attributes, their types and initial constraints Can optionally specify schema: CREATE TABLE COMPANY.EMPLOYEE... or CREATE TABLE EMPLOYEE... 4 The CREATE TABLE Command in SQL CREATE TABLE "table_name" ("column1" "data type", "column2" "data type", "column3" "data type"); 5 The CREATE TABLE Command in SQL CREATE TABLE employee (first varchar(15), last varchar(20), age int(3), address varchar(30)); 6
The CREATE TABLE Command in SQL Base tables (base relations) Relation and its tuples are actually created and stored as a file by the DBMS Virtual relations (views) Created through the CREATE VIEW statement. Do not correspond to any physical file. 7 The CREATE VIEW Command in SQL CREATE VIEW view_name AS SELECT column1,column2,... FROM table_name WHERE condition; 8 Basic data types Numeric data types Integer numbers: INTEGER, INT, and SMALLINT Floating-point (real) numbers: FLOAT or REAL, and DOUBLE PRECISION Character-string data types Fixed length: CHAR(n), CHARACTER(n) Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER VARYING(n) 9
Numeric data types Integer numbers: INTEGER(p): Precision p TINYINT: Precision 3 SMALLINT: Precision 5 MEDIUMINT: Precision 7 INTEGER, INT: Precision 10 BIGINT: Precision 19 10 Numeric data types Type Storage Minimum Value Maximum Value (Bytes) (Signed/Unsigned) (Signed/Unsigned) TINYINT 1-128 127 0 255 SMALLINT 2-32768 32767 0 65535 MEDIUMINT 3-8388608 8388607 0 16777215 INT 4-2147483648 2147483647 0 4294967295 BIGINT 8-9223372036854775808 9223372036854775807 0 18446744073709551615 11 Numeric data types Floating-point (real) numbers: FLOAT, mantissa precision 16 -(Approximate Value) DOUBLE, mantissa precision 16 -(Approximate Value) REAL, mantissa precision 7 -(Approximate Value) DECIMAL, mantissa precision 16 -(Exact Value) 12
Numeric data types Floating-point (real) numbers: MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE(M,D). Here, (M,D) means than values can be stored with up to M digits in total, of which D digits may be after the decimal point. 13 FLOAT(4,2) (a) (b) (c) 7689.23 76.89 76.8923 14 Numeric data types Floating-point (real) numbers: For example, a column defined as FLOAT(7,4) will look like -999.9999 when displayed. MySQL performs rounding when storing values, so if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001. 15
Boolean data type Values of TRUE or FALSE or NULL Valid examples Invalid examples TRUE 1 true yes FALSE 0 false no 16 Basic data types Character-string data types Fixed length: CHAR(n), CHARACTER(n) Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER VARYING(n) 17 Basic data types Character-string data types Value CHAR(4) VARCHAR(4) '' ' ' '' 'ab' 'ab ' 'ab' 'abcd' 'abcd' 'abcd' 'abcdefgh' 'abcd' 'abcd' 18
Date and Time Types The date and time types for representing temporal values are DATE, TIME, DATETIME, TIMESTAMP, and YEAR. Each temporal type has a range of valid values, as well as a zero value that may be used when you specify an invalid value that SQL cannot represent. 19 Date and Time Types Date parts must always be given in year-monthday order (for example, '98-09-04'), rather than in the month-day-year or day-month-year orders commonly used elsewhere (for example, '09-04-98', '04-09-98'). 20 Date and Time Types Dates containing two-digit year values are ambiguous. MySQL interprets two-digit year values using these rules: Year values in the range 70-99 are converted to 1970-1999. Year values in the range 00-69 are converted to 2000-2069. 21
Date and Time Types MySQL permits you to store a zero value of '0000-00-00' as a dummy date. This is in some cases more convenient than using NULL values, and uses less data and index space. To disallow '0000-00-00', enable the NO_ZERO_DATE mode. 22 Date and Time Types Data Type Zero Value DATE '0000-00-00' TIME '00:00:00' DATETIME '0000-00-00 00:00:00' TIMESTAMP '0000-00-00 00:00:00' YEAR 0000 23 Quiz 24
Specifying Constraints in SQL Basic constraints: Relational Model has 3 basic constraint types that are supported in SQL: Key constraint: A primary key value cannot be duplicated Entity Integrity Constraint: A primary key value cannot be null Referential integrity constraints: The foreign key must have a value that is already present as a primary key. 25 Specifying Attribute Constraints Other Restrictions on attribute domains: Default value of an attribute DEFAULT <value> NULL is not permitted for a particular attribute NOT NULL CHECK clause Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21); 26 Specifying Key and Referential Integrity Constraints PRIMARY KEY clause Specifies one or more attributes that make up the primary key of a relation D_number INT PRIMARY KEY; UNIQUE clause Specifies alternate (secondary) keys (called CANDIDATE keys in the relational model). D_name VARCHAR(15) UNIQUE; 27
Specifying Key and Referential Integrity Constraints FOREIGN KEY clause Default operation: reject update on violation Attach referential triggered action clause Options include SET NULL, CASCADE, and SET DEFAULT Action taken by the DBMS for SET NULL or SET DEFAULT is the same for both ON DELETE and ON UPDATE CASCADE option suitable for relationship relations 28 Basic Retrieval Queries in SQL SELECT statement One basic statement for retrieving information from a database 29 The SELECT-FROM-WHERE Structure of Basic SQL Queries Basic form of the SELECT statement: 30
The SELECT-FROM-WHERE Structure of Basic SQL Queries Logical comparison operators =, <, <=, >, >=, <> Projection attributes Attributes whose values are to be retrieved Selection condition Boolean condition that must be true for any retrieved tuple. 31 Basic Retrieval Queries 32 Basic Retrieval Queries 33
Basic Retrieval Queries Retrieve employee with salary more than 3000 34 Basic Retrieval Queries (Q0) 35 Basic Retrieval Queries (Q0) 36
Basic Retrieval Queries (Q1) 37 Basic Retrieval Queries (Q1) 38 Basic Retrieval Queries (Q2) 39
Basic Retrieval Queries (Q2) 40 Ambiguous Attribute Names Same name can be used for two (or more) attributes in different relations As long as the attributes are in different relations Must qualify the attribute name with the relation name to prevent ambiguity 41 Aliasing, and Renaming Aliases or tuple variables Declare alternative relation names E and S to refer to the EMPLOYEE relation twice in a query: Query 8. For each employee, retrieve the employee s first and last name and the first and last name of his or her immediate supervisor. SELECT E.Fname, E.Lname, S.Fname, S.Lname FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.Super_ssn = S.Ssn; 42
Unspecified WHERE Clause Missing WHERE clause Indicates no condition on tuple selection Effect is a CROSS PRODUCT Result is all possible tuple combinations result 43 Use of the Asterisk Specify an asterisk (*) Retrieve all the attribute values of the selected tuples The * can be prefixed by the relation name; e.g., EMPLOYEE * 44 Tables as Sets in SQL SQL does not automatically eliminate duplicate tuples in query results For aggregate operations duplicates must be accounted for Use the keyword DISTINCT in the SELECT clause Only distinct tuples should remain in the result 45