Data Definition Language SQL Domains Elementary Domains

Total Page:16

File Type:pdf, Size:1020Kb

Data Definition Language SQL Domains Elementary Domains SQL Week 2: Part II The name is an acronym for Structured Query SQL I – Data Definition Language Language. It is actually far richer than a query language: supports both a DML and a DDL. Domains, First proposal: SEQUEL (IBM Research, 1974); Schema Definitions, and First implementation in SQL/DS (IBM, 1981) Constraints Standardization crucial for its diffusion Since 1983, de facto standard; First official standard, 1986; revised in 1989; Second standard, 1992 (SQL-2 or SQL-92); Third standard, 1999 (SQL-3 or SQL-99) Most relational DBMS support the base functionality of the standard and offer proprietary extensions. CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 1 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 2 Domains Elementary Domains — Character Character Domains specify allowable values for attributes. Single characters or strings; Two categories: Strings may be of variable length; Elementary (predefined by the standard); A Character set different from the default one User-defined. can be used (e.g., Latin, Greek, Cyrillic, etc.) Syntax: character [ varying ] [ (Length) ] [ character set CharSetName ] It is possible to use char and varchar, for character and character varying respectively CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 3 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 4 1 More Elementary Domains Bit Approximate Numeric Domains Single Boolean values or strings of Boolean Approximate numeric domains values (may be variable in length); Approximate real values Syntax: Based on a floating point representation bit [ varying ] [ (Length) ] float [ ( Precision ) ] e.g., 0.17E16, 0.41E-6 Exact numeric domains double precision Exact values, integer or with a fractional part real — behaves like float, but has variable Four alternatives: numeric(6,3) precision numeric [ ( Precision [, Scale ] ) ] decimal [ ( Precision [, Scale ] ) ] integer smallint # of significant digits decimal digits CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 5 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 6 Temporal Instant Domains User-Defined Domains Temporal instants date has fields year,month,day Comparable to definitions of variable types in programming languages. time [ ( Precision) ][ with time zone ] has fields hour,minute,second A domain is characterized by name, elementary timestamp [ ( Precision) ] [ with time zone ] domain, default value, set of constraints Temporal intervals Syntax: create domain DomainName interval FirstUnitOfTime [ to LastUnitOfTime ] as ElementaryDomain [ DefaultValue ] [ Units of time are divided into two groups: (i) Constraints ] year, month, (ii) day, hour, minute, second Example: For example, allows year(5) to month create domain Mark as smallint intervals up to 99999yrs + 11mo default null CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 7 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 8 2 Default Domain Values Schema Definition Define the value that the attribute must assume when a value is not specified during row A schema is a collection of objects: domains, insertion. tables, indexes, assertions, views, privileges Syntax: A schema has a name and an owner (who default < GenericValue | user | null > determines authorization privileges) GenericValue represents a value compatible Syntax: with the domain, in the form of a constant or an create schema [ SchemaName ] expression. [ [ authorization ] Authorization ] user is the login name of the user who assigns { SchemaElementDefinition } a value to this attribute. CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 9 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 10 Table Definition Example of create table An SQL table consists of an ordered set of create table Employee attributes, and a (possibly empty) set of constraints ( RegNo character(6) primary key, Statement create table defines a relation FirstName character(20) not null, schema, creating an empty instance. Surname character(20) not null, Syntax: Dept character (15) create table TableName references Department(DeptName) on delete set null ( AttributeName Domain [ DefaultValue ] [ on update cascade, Constraints ] Salary numeric(9) default 0, {, AttributeName Domain [ DefaultValue ] [ City character(15), Constraints ] } unique(Surname,FirstName) [ OtherConstraints ] ) ) CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 11 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 12 3 Intra-Relational Constraints Example of Intra-Relational Constraints Constraints are conditions that must be verified by every database instance Each pair of FirstName and Surname uniquely Intra-relational constraints involve a single relation identifies each element not null (on single attributes) FirstName char(20) not null, unique: permits the definition of keys; syntax: Surname char(20) not null, unique(FirstName,Surname) for single attributes: unique, after the domain Note the difference with the following (stricter) for multiple: unique ( Attribute {, Attribute } ) definition: primary key: defines the primary key (once for FirstName char(20) not null unique, each table; implies not null); syntax like unique Surname char(20) not null unique, check: described later … CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 13 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 14 Inter-Relational Constraints Reaction Policies Constraints may involve several relations: Violations arise from check: checks whether an assertion is true; (a) updates on referred attribute or (b) row deletions. references and foreign key permit the Reactions operate on internal table, after changes to definition of referential integrity constraints; an external table. Syntax for single attributes Reactions are: references after the domain cascade: propagate the change; set null: nullify the referring attribute; Syntax for multiple attributes set default: assign default value to the foreign key ( Attribute {, Attribute } ) referring attribute; references ... no action: forbid the change on external table. It is possible to associate reaction policies to Reactions may depend on the event; syntax: violations of referential integrity constraints. on < delete | update > < cascade | set null | set default | no action > CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 15 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 16 4 Example Schema Updates create table Employee ( Two SQL statements: RegNo char(6), ( ) FirstName char(20) not null, alter alter domain...,alter table … Surname char(20) not null, drop < schema | domain | table | view | Dept char(15), assertion > Salary numeric(9) default 0, | City char(15), How else could we ComponentName [ restrict cascade ] primary key(RegNo), have identified the Examples: foreign key(Dept) primary key? references Department(DeptName) alter table Department How else could we on delete set null add column NoOfOffices numeric(4) have identified the on update cascade, primary key? unique(FirstName,Surname) drop table TempTable cascade ) CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 17 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 18 Column Relational Catalogues TableNm ColName Pos Default Nullable Employee RegNo 1 Null N A relational catalogue contains the data Employee Name 2 Null Y dictionary, i.e., a description of the relational Employee Dept 3 Null Y A schema D of the database. Employee Sal 4 0 Y Dept Name 1 Null N Relational It is based on a relational schema MD whose relations describe the relations, columns, Dept Head 2 Null Y Catalogue domains in D but also MD (reflectivity). Dept Address 3 Null Y Column TableNm 1 Null N The SQL-2 standard describes a Column ColName 2 Null N Definition_Schema (composed of tables) and an Column Pos 3 Null N Information_Schema (composed of views). Column Default 4 Null Y Column Nullable 5 Y N CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 19 CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 20 5 Practise What is the DDL for the database schema store containing Employee and Dept on the previous slide? 1.)create DDL to schemacreate store schema { 2.) create tablecreate Employee Employee ( table RegNo(We char(6), can take this from a previous slide) FirstName char(20) not null, Surname char(20) not null, Dept char(15), Salary numeric(9) default 0, City char(15), primary key(RegNo), foreign key(Dept) references Dept(DeptName) on delete set null on update cascade, unique(FirstName,Surname) ) 3.) create tablecreate Dept(( Dept table Name char(20)add fields primary key, Head char(6)remember references to add keys, foreignEmployee(RegNo) references, and on delete set null constraintson to updateensure integrity cascade, Address char(20) ) } CSC343 Introduction to Databases — University of Toronto SQL I: DDL — 21 6.
Recommended publications
  • Schema in Database Sql Server
    Schema In Database Sql Server Normie waff her Creon stringendo, she ratten it compunctiously. If Afric or rostrate Jerrie usually files his terrenes shrives wordily or supernaturalized plenarily and quiet, how undistinguished is Sheffy? Warring and Mahdi Morry always roquet impenetrably and barbarizes his boskage. Schema compare tables just how the sys is a table continues to the most out longer function because of the connector will often want to. Roles namely actors in designer slow and target multiple teams together, so forth from sql management. You in sql server, should give you can learn, and execute this is a location of users: a database projects, or more than in. Your sql is that the view to view of my data sources with the correct. Dive into the host, which objects such a set of lock a server database schema in sql server instance of tables under the need? While viewing data in sql server database to use of microseconds past midnight. Is sql server is sql schema database server in normal circumstances but it to use. You effectively structure of the sql database objects have used to it allows our policy via js. Represents table schema in comparing new database. Dml statement as schema in database sql server functions, and so here! More in sql server books online schema of the database operator with sql server connector are not a new york, with that object you will need. This in schemas and history topic names are used to assist reporting from. Sql schema table as views should clarify log reading from synonyms in advance so that is to add this game reports are.
    [Show full text]
  • Referential Integrity in Sqlite
    CS 564: Database Management Systems University of Wisconsin - Madison, Fall 2017 Referential Integrity in SQLite Declaring Referential Integrity (Foreign Key) Constraints Foreign key constraints are used to check referential integrity between tables in a database. Consider, for example, the following two tables: create table Residence ( nameVARCHARPRIMARY KEY, capacityINT ); create table Student ( idINTPRIMARY KEY, firstNameVARCHAR, lastNameVARCHAR, residenceVARCHAR ); We can enforce the constraint that a Student’s residence actually exists by making Student.residence a foreign key that refers to Residence.name. SQLite lets you specify this relationship in several different ways: create table Residence ( nameVARCHARPRIMARY KEY, capacityINT ); create table Student ( idINTPRIMARY KEY, firstNameVARCHAR, lastNameVARCHAR, residenceVARCHAR, FOREIGNKEY(residence) REFERENCES Residence(name) ); or create table Residence ( nameVARCHARPRIMARY KEY, capacityINT ); create table Student ( idINTPRIMARY KEY, firstNameVARCHAR, lastNameVARCHAR, residenceVARCHAR REFERENCES Residence(name) ); or create table Residence ( nameVARCHARPRIMARY KEY, 1 capacityINT ); create table Student ( idINTPRIMARY KEY, firstNameVARCHAR, lastNameVARCHAR, residenceVARCHAR REFERENCES Residence-- Implicitly references the primary key of the Residence table. ); All three forms are valid syntax for specifying the same constraint. Constraint Enforcement There are a number of important things about how referential integrity and foreign keys are handled in SQLite: • The attribute(s) referenced by a foreign key constraint (i.e. Residence.name in the example above) must be declared UNIQUE or as the PRIMARY KEY within their table, but this requirement is checked at run-time, not when constraints are declared. For example, if Residence.name had not been declared as the PRIMARY KEY of its table (or as UNIQUE), the FOREIGN KEY declarations above would still be permitted, but inserting into the Student table would always yield an error.
    [Show full text]
  • (DDL) Reference Manual
    Data Definition Language (DDL) Reference Manual Abstract This publication describes the DDL language syntax and the DDL dictionary database. The audience includes application programmers and database administrators. Product Version DDL D40 DDL H01 Supported Release Version Updates (RVUs) This publication supports J06.03 and all subsequent J-series RVUs, H06.03 and all subsequent H-series RVUs, and G06.26 and all subsequent G-series RVUs, until otherwise indicated by its replacement publications. Part Number Published 529431-003 May 2010 Document History Part Number Product Version Published 529431-002 DDL D40, DDL H01 July 2005 529431-003 DDL D40, DDL H01 May 2010 Legal Notices Copyright 2010 Hewlett-Packard Development Company L.P. Confidential computer software. Valid license from HP required for possession, use or copying. Consistent with FAR 12.211 and 12.212, Commercial Computer Software, Computer Software Documentation, and Technical Data for Commercial Items are licensed to the U.S. Government under vendor's standard commercial license. The information contained herein is subject to change without notice. The only warranties for HP products and services are set forth in the express warranty statements accompanying such products and services. Nothing herein should be construed as constituting an additional warranty. HP shall not be liable for technical or editorial errors or omissions contained herein. Export of the information contained in this publication may require authorization from the U.S. Department of Commerce. Microsoft, Windows, and Windows NT are U.S. registered trademarks of Microsoft Corporation. Intel, Itanium, Pentium, and Celeron are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries.
    [Show full text]
  • 2. Creating a Database Designing the Database Schema
    2. Creating a database Designing the database schema ..................................................................................... 1 Representing Classes, Attributes and Objects ............................................................. 2 Data types .......................................................................................................................... 5 Additional constraints ...................................................................................................... 6 Choosing the right fields ................................................................................................. 7 Implementing a table in SQL ........................................................................................... 7 Inserting data into a table ................................................................................................ 8 Primary keys .................................................................................................................... 10 Representing relationships ........................................................................................... 12 Altering a table ................................................................................................................ 22 Designing the database schema As you have seen, once the data model for a system has been designed, you need to work out how to represent that model in a relational database. This representation is sometimes referred to as the database schema. In a relational database, the schema defines
    [Show full text]
  • The Unconstrained Primary Key
    IBM Systems Lab Services and Training The Unconstrained Primary Key Dan Cruikshank www.ibm.com/systems/services/labservices © 2009 IBM Corporation In this presentation I build upon the concepts that were presented in my article “The Keys to the Kingdom”. I will discuss how primary and unique keys can be utilized for something other than just RI. In essence, it is about laying the foundation for data centric programming. I hope to convey that by establishing some basic rules the database developer can obtain reasonable performance. The title is an oxymoron, in essence a Primary Key is a constraint, but it is a constraint that gives the database developer more freedom to utilize an extremely powerful relational database management system, what we call DB2 for i. 1 IBM Systems Lab Services and Training Agenda Keys to the Kingdom Exploiting the Primary Key Pagination with ROW_NUMBER Column Ordering Summary 2 www.ibm.com/systems/services/labservices © 2009 IBM Corporation I will review the concepts I introduced in the article “The Keys to the Kingdom” published in the Centerfield. I think this was the inspiration for the picture. I offered a picture of me sitting on the throne, but that was rejected. I will follow this with a discussion on using the primary key as a means for creating peer or subset tables for the purpose of including or excluding rows in a result set. The ROW_NUMBER function is part of the OLAP support functions introduced in 5.4. Here I provide some examples of using ROW_NUMBER with the BETWEEN predicate in order paginate a result set.
    [Show full text]
  • Keys Are, As Their Name Suggests, a Key Part of a Relational Database
    The key is defined as the column or attribute of the database table. For example if a table has id, name and address as the column names then each one is known as the key for that table. We can also say that the table has 3 keys as id, name and address. The keys are also used to identify each record in the database table . Primary Key:- • Every database table should have one or more columns designated as the primary key . The value this key holds should be unique for each record in the database. For example, assume we have a table called Employees (SSN- social security No) that contains personnel information for every employee in our firm. We’ need to select an appropriate primary key that would uniquely identify each employee. Primary Key • The primary key must contain unique values, must never be null and uniquely identify each record in the table. • As an example, a student id might be a primary key in a student table, a department code in a table of all departments in an organisation. Unique Key • The UNIQUE constraint uniquely identifies each record in a database table. • Allows Null value. But only one Null value. • A table can have more than one UNIQUE Key Column[s] • A table can have multiple unique keys Differences between Primary Key and Unique Key: • Primary Key 1. A primary key cannot allow null (a primary key cannot be defined on columns that allow nulls). 2. Each table can have only one primary key. • Unique Key 1. A unique key can allow null (a unique key can be defined on columns that allow nulls.) 2.
    [Show full text]
  • A Relational Multi-Schema Data Model and Query Language for Full Support of Schema Versioning?
    A Relational Multi-Schema Data Model and Query Language for Full Support of Schema Versioning? Fabio Grandi CSITE-CNR and DEIS, Alma Mater Studiorum – Universita` di Bologna Viale Risorgimento 2, 40136 Bologna, Italy, email: [email protected] Abstract. Schema versioning is a powerful tool not only to ensure reuse of data and continued support of legacy applications after schema changes, but also to add a new degree of freedom to database designers, application developers and final users. In fact, different schema versions actually allow one to represent, in full relief, different points of view over the modelled application reality. The key to such an improvement is the adop- tion of a multi-pool implementation solution, rather that the single-pool solution usually endorsed by other authors. In this paper, we show some of the application potentialities of the multi-pool approach in schema versioning through a concrete example, introduce a simple but comprehensive logical storage model for the mapping of a multi-schema database onto a standard relational database and use such a model to define and exem- plify a multi-schema query language, called MSQL, which allows one to exploit the full potentialities of schema versioning under the multi-pool approach. 1 Introduction However careful and accurate the initial design may have been, a database schema is likely to undergo changes and revisions after implementation. In order to avoid the loss of data after schema changes, schema evolution has been introduced to provide (partial) automatic recov- ery of the extant data by adapting them to the new schema.
    [Show full text]
  • Pizza Parlor Point-Of-Sales System CMPS 342 Database
    1 Pizza Parlor Point-Of-Sales System CMPS 342 Database Systems Chris Perry Ruben Castaneda 2 Table of Contents PHASE 1 1 Pizza Parlor: Point-Of-Sales Database........................................................................3 1.1 Description of Business......................................................................................3 1.2 Conceptual Database.........................................................................................4 2 Conceptual Database Design........................................................................................5 2.1 Entities................................................................................................................5 2.2 Relationships....................................................................................................13 2.3 Related Entities................................................................................................16 PHASE 2 3 ER-Model vs Relational Model..................................................................................17 3.1 Description.......................................................................................................17 3.2 Comparison......................................................................................................17 3.3 Conversion from E-R model to relational model.............................................17 3.4 Constraints........................................................................................................19 4 Relational Model..........................................................................................................19
    [Show full text]
  • Data Definition Language
    1 Structured Query Language SQL, or Structured Query Language is the most popular declarative language used to work with Relational Databases. Originally developed at IBM, it has been subsequently standard- ized by various standards bodies (ANSI, ISO), and extended by various corporations adding their own features (T-SQL, PL/SQL, etc.). There are two primary parts to SQL: The DDL and DML (& DCL). 2 DDL - Data Definition Language DDL is a standard subset of SQL that is used to define tables (database structure), and other metadata related things. The few basic commands include: CREATE DATABASE, CREATE TABLE, DROP TABLE, and ALTER TABLE. There are many other statements, but those are the ones most commonly used. 2.1 CREATE DATABASE Many database servers allow for the presence of many databases1. In order to create a database, a relatively standard command ‘CREATE DATABASE’ is used. The general format of the command is: CREATE DATABASE <database-name> ; The name can be pretty much anything; usually it shouldn’t have spaces (or those spaces have to be properly escaped). Some databases allow hyphens, and/or underscores in the name. The name is usually limited in size (some databases limit the name to 8 characters, others to 32—in other words, it depends on what database you use). 2.2 DROP DATABASE Just like there is a ‘create database’ there is also a ‘drop database’, which simply removes the database. Note that it doesn’t ask you for confirmation, and once you remove a database, it is gone forever2. DROP DATABASE <database-name> ; 2.3 CREATE TABLE Probably the most common DDL statement is ‘CREATE TABLE’.
    [Show full text]
  • Drawing-A-Database-Schema.Pdf
    Drawing A Database Schema Padraig roll-out her osteotome pluckily, trillion and unacquainted. Astronomic Dominic haemorrhage operosely. Dilative Parrnell jury-rigging: he bucketing his sympatholytics tonishly and litho. Publish your schema. And database user schema of databases in berlin for your drawing created in a diagram is an er diagram? And you know some they say, before what already know. You can generate the DDL and modify their hand for SQLite, although to it ugly. How can should improve? This can work online, a record is crucial to reduce faults in. The mouse pointer should trace to an icon with three squares. Visual Database Creation with MySQL Workbench Code. In database but a schema pronounced skee-muh or skee-mah is the organisation and structure of a syringe Both schemas and. Further more complex application performance, concept was that will inform your databases to draw more control versions. Typically goes in a schema from any sql for these terms of maintenance of the need to do you can. Or database schemas you draw data models commonly used to select all databases by drawing page helpful is in a good as methods? It is far to bath to target what suits you best. Gallery of training courses. Schema for database schema for. Help and Training on mature site? You can jump of ER diagrams as a simplified form let the class diagram and carpet may be easier for create database design team members to. This token will be enrolled in quickly create drawings by enabled the left side of the process without realising it? Understanding a Schema in Psychology Verywell Mind.
    [Show full text]
  • Chapter 2: Database System Concepts and Architecture Define
    Chapter 2: Database System Concepts and Architecture define: data model - set of concepts that can be used to describe the structure of a database data types, relationships and constraints set of basic operations - retrievals and updates specify behavior - set of valid user-defined operations categories: high-level (conceptual data model) - provides concepts the way a user perceives data - entity - real world object or concept to be represented in db - attribute - some property of the entity - relationship - represents and interaction among entities representational (implementation data model) - hide some details of how data is stored, but can be implemented directly - record-based models like relational are representational low-level (physical data model) - provides details of how data is stored - record formats - record orderings - access path (for efficient search) schemas and instances: database schema - description of the data (meta-data) defined at design time each object in schema is a schema construct EX: look at TOY example - top notation represents schema schema constructs: cust ID; order #; etc. database state - the data in the database at any particular time - also called set of instances an instance of data is filled when database is populated/updated EX: cust name is a schema construct; George Grant is an instance of cust name difference between schema and state - at design time, schema is defined and state is the empty state - state changes each time data is inserted or updated, schema remains the same Three-schema architecture
    [Show full text]
  • Database Schema
    Database Schema • About Database Schema, page 1 • Data Model Diagram, page 3 • Unified Customer Voice Portal Reporting Data Model, page 5 • Cisco Unified Customer Voice Portal Database Tables, page 8 • Call Tables, page 9 • VXML Tables, page 14 • Summary / Aggregate Tables, page 25 • Lookup and Reference Tables, page 34 • Courtesy CallBack Tables, page 45 About Database Schema The Cisco Unified Customer Voice Portal (United CVP) reporting server hosts an IBM Informix Dynamic Server (IDS) database, which stores reporting data in a defined database schema. Customers who choose to deploy Cisco Unified Intelligence Center (Unified Intelligence Center) as their reporting platform must add the Informix database as a data source in Unified Intelligence Center. The schema is fully published so that customers can develop custom reports. Customers may not, however, extend the schema for their own purposes. The schema provides Unified CVP customers with the ability to: • Establish database connectivity with Unified Intelligence Center and to import and run the Unified CVP templates with Unified Intelligence Center. • Establish database connectivity with other commercial off-the-shelf reporting and analytics engines and then build custom reports against the Unified CVP database schema. Note Your support provider cannot assist you with custom reports or with commercial (non-Cisco) reporting products. Reporting Guide for Cisco Unified Customer Voice Portal, Release 10.5(1) 1 Database Schema About Database Schema The following diagram indicates a common set of incoming and outgoing entry and exit states for a call to a self-service application. Figure 1: Call Flow Note When basic video is transferred to an audio-only agent, the call remains classified as basic video accepted.
    [Show full text]