Structured Query Language - Halvorsen.blog

Transcription

https://www.halvorsen.blogStructured Query LanguageHans-Petter HalvorsenAvailable Online: https://www.halvorsen.blog

Structured Query LanguageHans-Petter HalvorsenCopyright 2017https://www.halvorsen.blog

Table of Contents12Introduction to SQL . 61.1Data Definition Language (DDL). 81.2Data Manipulation Language (DML) . 8Introduction to SQL Server . 92.13SQL Server Management Studio . 102.1.1Create a new Database. 112.1.2Queries . 12CREATE TABLE . 133.1Database Modelling . 153.2Create Tables using the Designer Tools . 173.3SQL Constraints . 173.3.1PRIMARY KEY . 183.3.2FOREIGN KEY . 193.3.3NOT NULL / Required Columns . 223.3.4UNIQUE . 233.3.5CHECK . 253.3.6DEFAULT . 273.3.7AUTO INCREMENT or IDENTITY . 283.4ALTER TABLE . 294INSERT INTO . 315UPDATE . 333

4Table of Contents6DELETE . 357SELECT . 377.1The ORDER BY Keyword . 397.2SELECT DISTINCT . 407.3The WHERE Clause . 407.3.1Operators . 417.3.2LIKE Operator . 417.3.3IN Operator. 427.3.4BETWEEN Operator . 427.4Wildcards . 427.5AND & OR Operators . 437.6SELECT TOP Clause . 447.7Alias . 457.8Joins . 457.8.18Different SQL JOINs . 46SQL Scripts . 488.1Using Comments . 488.1.1Single-line comment . 488.1.2Multiple-line comment . 488.2Variables . 498.3Built-in Global Variables . 508.3.18.4@@IDENTITY . 50Flow Control . 518.4.1IF – ELSE . 518.4.2WHILE . 528.4.3CASE. 53Structured Query Language (SQL)

5Table of Contents8.4.49CURSOR . 54Views . 569.110Using the Graphical Designer . 57Stored Procedures . 6110.111NOCOUNT ON/NOCOUNT OFF . 64Functions . 6611.1Built-in Functions . 6611.1.1String Functions . 6611.1.2Date and Time Functions . 6711.1.3Mathematics and Statistics Functions . 6711.1.4AVG() . 6811.1.5COUNT() . 6811.1.6The GROUP BY Statement. 6911.1.7The HAVING Clause . 7011.2User-defined Functions . 7112Triggers . 7213Communication from other Applications . 7513.1ODBC . 7513.2Microsoft Excel . 7614References . 78Structured Query Language (SQL)

1 Introduction to SQLSQL (Structured Query Language) is a database computer language designed for managingdata in relational database management systems (RDBMS).SQL, is a standardized computer language that was originally developed by IBM for querying,altering and defining relational databases, using declarative statements.SQL is pronounced /ˌɛs kjuː ˈɛl/ (letter by letter) or /ˈsiːkwəl/ (as a word).What can SQL do? SQL can execute queries against a databaseSQL can retrieve data from a databaseSQL can insert records in a databaseSQL can update records in a databaseSQL can delete records from a database6

7Introduction to SQL SQL can create new databasesSQL can create new tables in a databaseSQL can create stored procedures in a databaseSQL can create views in a databaseSQL can set permissions on tables, procedures, and viewsEven if SQL is a standard, many of the database systems that exist today implement theirown version of the SQL language. In this document, we will use the Microsoft SQL Server asan example.There are lots of different database systems, or DBMS – Database Management Systems,such as: Microsoft SQL Servero Enterprise, Developer versions, etc.o Express version is free of chargeOracleMySQL (Oracle, previously Sun Microsystems) - MySQL can be used free of charge(open source license), Web sites that use MySQL: YouTube, Wikipedia, FacebookMicrosoft AccessIBM DB2Sybase lots of other systemsIn this Tutorial, we will focus on Microsoft SQL Server. SQL Server uses T-SQL (Transact-SQL).T-SQL is Microsoft's proprietary extension to SQL. T-SQL is very similar to standard SQL, butin addition it supports some extra functionality, built-in functions, etc.Structured Query Language (SQL)

8Introduction to SQLOther useful Tutorials about databases: Introduction to Database SystemsDatabase Communication in LabVIEWThese Tutorials are located at: https://www.halvorsen.blog1.1 Data Definition Language (DDL)The Data Definition Language (DDL) manages table and index structure. The most basicitems of DDL are the CREATE, ALTER, RENAME and DROP statements: CREATE creates an object (a table, for example) in the database.DROP deletes an object in the database, usually irretrievably.ALTER modifies the structure an existing object in various ways—for example, addinga column to an existing table.1.2 Data Manipulation Language (DML)The Data Manipulation Language (DML) is the subset of SQL used to add, update and deletedata.The acronym CRUD refers to all of the major functions that need to be implemented in arelational database application to consider it complete. Each letter in the acronym can bemapped to a standard SQL statement:OperationCreateSQLINSERT INTORead (Retrieve)UpdateDelete (Destroy)SELECTUPDATEDELETEDescriptioninserts new data into adatabaseextracts data from a databaseupdates data in a databasedeletes data from a databaseStructured Query Language (SQL)

2 Introduction to SQL ServerMicrosoft is the vendor of SQL Server.We have different editions of SQL Server, where SQL Server Express is free to download anduse.SQL Server uses T-SQL (Transact-SQL). T-SQL is Microsoft's proprietary extension to SQL. TSQL is very similar to standard SQL, but in addition it supports some extra functionality, builtin functions, etc. T-SQL expands on the SQL standard to include procedural programming,local variables, various support functions for string processing, date processing,mathematics, etc.SQL Server consists of a Database Engine and a Management Studio (and lots of other stuffwhich we will not mention here). The Database engine has no graphical interface - it is just aservice running in the background of your computer (preferable on the server). TheManagement Studio is graphical tool for configuring and viewing the information in thedatabase. It can be installed on the server or on the client (or both).9

10Introduction to SQL Server2.1 SQL Server Management StudioSQL Server Management Studio is a GUI tool included with SQL Server for configuring,managing, and administering all components within Microsoft SQL Server. The tool includesboth script editors and graphical tools that work with objects and features of the server. Asmentioned earlier, version of SQL Server Management Studio is also available for SQL ServerExpress Edition, for which it is known as SQL Server Management Studio Express.A central feature of SQL Server Management Studio is the Object Explorer, which allows theuser to browse, select, and act upon any of the objects within the server. It can be used tovisually observe and analyze query plans and optimize the database performance, amongothers. SQL Server Management Studio can also be used to create a new database, alter anyexisting database schema by adding or modifying tables and indexes, or analyzeperformance. It includes the query windows which provide a GUI based interface to writeand execute queries.When creating SQL commands and queries, the “Query Editor” (select “New Query” fromthe Toolbar) is used (shown in the figure above).With SQL and the “Query Editor” we can do almost everything with code, but sometimes it isalso a good idea to use the different Designer tools in SQL to help us do the work withoutcoding (so much).Structured Query Language (SQL)

112.1.1Introduction to SQL ServerCreate a new DatabaseIt is quite simple to create a new database in Microsoft SQL Server. Just right-click on the“Databases” node and select “New Database ”There are lots of settings you may set regarding your database, but the only information youmust fill in is the name of your database:Structured Query Language (SQL)

12Introduction to SQL ServerYou may also use the SQL language to create a new database, but sometimes it is easier tojust use the built-in features in the Management Studio.2.1.2QueriesIn order to make a new SQL query, select the “New Query” button from the Toolbar.Here we can write any kind of queries that is supported by the SQL language.Structured Query Language (SQL)

3 CREATE TABLEBefore you start implementing your tables in the database, you should always spend sometime design your tables properly using a design tool like, e.g., ERwin, Toad Data Modeler,PowerDesigner, Visio, etc. This is called Database Modeling.The CREATE TABLE statement is used to create a table in a database.Syntax:CREATE TABLE(column name1column name2column name3.)table namedata type,data type,data type,The data type specifies what type of data the column can hold.13

14CREATE TABLEYou have special data types for numbers, text dates, etc.Examples: Numbers: int, floatText/Stings: varchar(X) – where X is the length of the stringDates: datetimeetc.Example:We want to create a table called “CUSTOMER” which has the following columns and datatypes:CREATE TABLE CUSTOMER(CustomerId int IDENTITY(1,1) PRIMARY KEY,CustomerNumber int NOT NULL UNIQUE,LastName varchar(50) NOT NULL,FirstName varchar(50) NOT NULL,AreaCode int NULL,Address varchar(50) NULL,Phone varchar(50) NULL,)GOBest practice:When creating tables you should consider following these guidelines: Tables: Use upper case and singular form in table names – not plural, e.g.,“STUDENT” (not students)Columns: Use Pascal notation, e.g., “StudentId”Primary Key:o If the table name is “COURSE”, name the Primary Key column “CourseId”, etc.Structured Query Language (SQL)

15CREATE TABLE“Always” use Integer and Identity(1,1) for Primary Keys. Use UNIQUEconstraint for other columns that needs to be unique, e.g. RoomNumberSpecify Required Columns (NOT NULL) – i.e., which columns that need to have dataor notStandardize on few/these Data Types: int, float, varchar(x), datetime, bitUse English for table and column namesAvoid abbreviations! (Use RoomNumber – not RoomNo, RoomNr, .)o 3.1 Database ModellingAs mention in the beginning of the chapter, you should always start with database modellingbefore you start implementing the tables in a database system.Below we see a database model in created with ERwin.With this tool we can transfer the database model as tables into different database systems,such as e.g., SQL Server. CA ERwin Data Modeler Community Edition is free with a 25 objectslimit. It has support for Oracle, SQL Server, MySQL, ODBC and Sybase.Structured Query Language (SQL)

16CREATE TABLEBelow we see the same tables inside the design tool in SQL Server.Structured Query Language (SQL)

17CREATE TABLE3.2 Create Tables using the Designer ToolsEven if you can do “everything” using the SQL language, it is sometimes easier to do it in thedesigner tools in the Management Studio in SQL Server.Instead of creating a script you may as well easily use the designer for creating tables.Step1: Select “New Table ”:Step2: Next, the table designer pops up where you can add columns, data types, etc.In this designer we may also specify Column Names, Data Types, etc.Step 3: Save the table by clicking the Save button.3.3 SQL ConstraintsConstraints are used to limit the type of data that can go into a table.Structured Query Language (SQL)

18CREATE TABLEConstraints can be specified when a table is created (with the CREATE TABLE statement) orafter the table is created (with the ALTER TABLE statement).Here are the most important constraints: PRIMARY KEYNOT NULLUNIQUEFOREIGN KEYCHECKDEFAULTIDENTITYIn the sections below we will explain some of these in detail.3.3.1PRIMARY KEYThe PRIMARY KEY constraint uniquely identifies each record in a database table.Primary keys must contain unique values. It is normal to just use running numbers, like 1, 2,3, 4, 5, as values in Primary Key column. It is a good idea to let the system handle this foryou by specifying that the Primary Key should be set to identity(1,1). IDENTITY(1,1) meansthe first value will be 1 and then it will increment by 1.Each table should have a primary key, and each table can have only ONE primary key.If we take a closer look at the CUSTOMER table created earlier:CREATE TABLE [CUSTOMER](CustomerId int IDENTITY(1,1) PRIMARY KEY,CustomerNumber int NOT NULL UNIQUE,LastName varchar(50) NOT NULL,FirstName varchar(50) NOT NULL,AreaCode int NULL,Address varchar(50) NULL,Phone varchar(50) NULL,)GOAs you see we use the “Primary Key” keyword to specify that a column should be thePrimary Key.Structured Query Language (SQL)

19CREATE TABLESetting Primary Keys in the Designer Tools:If you use the Designer tools in SQL Server, you can easily set the primary Key in a table justby right-click and select “Set primary Key”.The primary Key column will then have a small keya Primary Key.3.3.2in front to illustrate that this column isFOREIGN KEYA FOREIGN KEY in one table points to a PRIMARY KEY in another table.Example:We will create a CREATE TABLE script for these tables:Structured Query Language (SQL)

20CREATE TABLESCHOOL:CREATE TABLE SCHOOL(SchoolId int IDENTITY(1,1) PRIMARY KEY,SchoolName varchar(50) NOT NULL UNIQUE,Description varchar(1000) NULL,Address varchar(50) NULL,Phone varchar(50) NULL,PostCode varchar(50) NULL,PostAddress varchar(50) NULL,)GOCLASS:CREATE TABLE CLASS(ClassId int IDENTITY(1,1) PRIMARY KEY,SchoolId int NOT NULL FOREIGN KEY REFERENCES SCHOOL (SchoolId),ClassName varchar(50) NOT NULL UNIQUE,Description varchar(1000) NULL,)GOThe FOREIGN KEY constraint is used to prevent actions that would destroy links betweentables.The FOREIGN

SQL (Structured Query Language) is a database computer language designed for managing data in relational database management systems (RDBMS). SQL, is a standardized computer language that was original