Obie  Beier

Obie Beier

1669107240

What Are SQL Constraints? Everything You Need to Know

What are SQL constraints?

SQL constraints are a set of rules implemented on tables in relational databases to dictate what data can be inserted, updated or deleted in its tables. This is done to ensure the accuracy and the reliability of information stored in the table. Constraints enforce limits to the data or type of data that can be inserted/updated/deleted from a table. The purpose of constraints is to maintain the data integrity during an update/delete/insert into a table.  Once the constraint is placed, if any operation in the database does not follow the rules specified by the constraint, the particular operation is aborted. In this article, we will go through what SQL constraints are, what are the different kinds of SQL constraints are commonly used and how to implement and get rid of them. First, however, we will take a brief look into why they are needed.

Need for SQL Constraints

Before we get into the details of what SQL constraints are, let’s take a look at why they are necessary. In order to arrive at that answer, we need to first understand the way in which information is stored in relational databases and why it is of primal importance to ensure that frameworks are in place governing what information can be entered or altered in a way that that information in the tables are not corrupted.

At a high level, information in relational databases is segregated into two types, facts and dimensions. Fact tables contain information relating to mathematical information, as a thumb rule, any information on which mathematical operations can be applied, are facts. Sales numbers, costs and revenues are examples of facts. Whereas information like name, date of birth, geographic location etc are examples of dimensional information. In an optimally normalised database, facts and dimensions are stored in separate tables. In order to facilitate rapid extraction of information, relations are built between particular columns in the fact and dimension tables.  This is where relational databases get their name from and it is on the basis of these relationships that multiple tables are joined and the data in the tables extracted. Fact and dimension tables are organized in particular structures known as schemas.  Star schema and snowflake schema are popular ways of organising this information.

Star Schema

A star schema is a database organisational structure optimised for use in a data warehouse or business intelligence that stores transactional or measured data in a single large fact table and attributes about the data in one or more smaller dimensional tables.

Snowflake Schema 

Generally, the association between fact and dimension tables happen via something called a PRIMARY KEY – FOREIGN KEY relationship. A PRIMARY KEY is a unique identifier of a particular row of information in a fact table, which connects to the FOREIGN KEY in a dimension table to identify dimension information for the same row in the dimension table. Since PRIMARY KEYS are unique identifiers for particular sets of information, for example, a particular sale in the Sales table, it is imperative that the PRIMARY KEY column in the table do not contain duplicates, that is, multiple sales cannot have the same unique ID. Also, values in the PRIMARY KEY column cannot be blank.  Otherwise, we wouldn’t be able to identify that particular Sale. So generally, there are rules placed on PRIMARY KEY columns in fact tables that ensure the column doesn’t contain duplicates and no row in the column is blank. This is a classic example of a SQL constraint!  Relational databases are quite fragile in the way that very small changes in the information stored in tables can upset the proper functioning of data storage and data extraction from the database.  SQL constraints are placed to ensure that insertions, updates, and deletion of information in a database occur in a way that the smooth functioning of the database is maintained.

Below is a list of common reasons why SQL constraints are applied on databases:

  • Prevent bad data from being entered into tables of interest.
  • Enforce business logic at the database level.
  • Documentation of important database rules.
  • Enforce relational integrity between any number of tables.
  • Improve database performance.
  • Enforce uniqueness.

Types of SQL Constraints

SQL constraints can be at a column or a table level. Column level constraints apply to specific columns in a table and do not specify a column name except the check constraints. They refer to the column that they follow. The names are specified by the Table-level constraints of the columns to which they apply.

Following is a list of the most commonly used column and table level SQL constraints:

Column Level Constraints include:

  • NOT NULL Constraint
  • UNIQUE Constraint
  • DEFAULT Constraint
  • CHECK Constraint
  • PRIMARY KEY Constraint
  • FOREIGN KEY Constraint

Column Level Constraints include:

  • UNIQUE Constraint
  • CHECK Constraint
  • PRIMARY KEY Constraint
  • FOREIGN KEY Constraint
  • INDEX Constraint

Let us now dive into the world of SQL constraints! We will browse in detail what each constraint is, why we use them and how to apply and remove them.

The NOT NULL Constraint

A NOT NULL constraint specifies that no cell value for any row in this column can be blank. Generally, this rule is applied to columns that capture information that is absolutely vital to identify and extract data from a table. Continuing the Sales table example, Sale_Id and the Sales_Amount would be potential columns for applying the NOT NULL constraint.

Applying the NOT NULL constraint:

The NOT NULL constraint can be defined either during the creation of the table or can be put in place later via an alter statement.

Declaring a NOT NULL Constraint during the Creation of a Table:

The following SQL creates a NOT NULL constraint in the columns ‘Sale_Id’, ‘Sale_Amount’ and ‘Vendor_Name’ when the table ‘Sales’ is created:

1

2

3

4

5

6

7

CREATE TABLE Sales (

    Sale_Id int NOT NULL,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255) NOT NULL,

    Sale_Date date,

    Profit int

);

By specifying the words NOT NULL after the column definition, we create a ‘Sales’ table where the ‘Sale_Id’, ‘Sale_Amount’ and ‘Vendor_Name’ columns cannot be blank. The column ‘Profit’ can have null values.

Altering a NOT NULL Constraint after the Creation of a Table:

Consider, that after the creation of the ‘Sales’ table and storing information in the same, business logic changes and now we’re instructed that no sales can be recorded in the ‘Sales’ table without recording the amount of profit that was earned on the sale. In that case, we will now have to add a constraint that the profit column cannot be null. This is how we would do it:

1

2

ALTER TABLE Sales

MODIFY Profit int NOT NULL;

The UNIQUE Constraint 

The UNIQUE constraint specifies that no cell value in a column can be repeated throughout the table.  That is, each row for this column in the table has to be unique and non-repetitive. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint has a UNIQUE constraint automatically. However, you can have many UNIQUE constraints in a table, but only one PRIMARY KEY constraint can be there in one table.

Applying the UNIQUE constraint:

The UNIQUE constraint can be defined either during the creation of the table or can be put in place later via an alter statement.

Declaring a UNIQUE Constraint during the Creation of a Table:

The following SQL creates a UNIQUE constraint in the columns ‘Sale_Id’ when the table ‘Sales’ is created in various relational databases:

SQL Server / Oracle / MS Access:

1

2

3

4

5

6

7

CREATE TABLE Sales (

    Sale_Id int NOT NULL UNIQUE,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255) NOT NULL,

    Sale_Date date,

    Profit int

);

MySQL:

1

2

3

4

5

6

7

8

CREATE TABLE Sales (

    Sale_Id int NOT NULL,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255) NOT NULL,

    Sale_Date date,

    Profit int,

    UNIQUE(Sale_Id)

);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the following SQL syntax:

SQL Server / Oracle / MS Access:

1

2

3

4

5

6

7

CREATE TABLE Sales (

    Sale_Id int NOT NULL,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255) NOT NULL,

    Sale_Date date,

    Profit int,

    CONSTRAINT UC_Sales UNIQUE (Sale_Id,Sale_Amount));

Altering a UNIQUE Constraint after the Creation of a Table:

To create a UNIQUE constraint on the “Sale_Id” column when the table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales

ADD UNIQUE(Sale_Id);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales

ADD CONSTRAINT UC_Sales UNIQUE(Sale_Id,Sale_Amount);

Dropping a UNIQUE Constraint:

To drop a UNIQUE constraint, we will need to specify the naming convention that was used during the creation of the constraint:

MySQL:

1

2

ALTER TABLE Sales

DROP INDEX UC_Sales;

SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales

DROP CONSTRAINT UC_Sales;

The CHECK Constraint 

The CHECK constraint is used to ensure that all the records in a certain column follow a specific rule. Generally, this constraint is used to enforce business logic on values in a column to make sure that no corrupt information is entered. For example, in the ‘Sales’ table,  let’s say that the business has specified a rule that sales made to a certain vendor ‘ABC’ should not be entered into the ‘Sales’ table. To ensure that sales to this vendor are not entered into our table, we add a CHECK constraint on the ‘Vendor_Name’ column which will reject any operation that tries to insert the value ‘ABC’ in the ‘Vendor_Name’ column.

Applying the CHECK Constraint:

The CHECK constraint can be defined either during the creation of the table or can be put in place later via an alter statement.

Declaring a CHECK Constraint during the Creation of a Table:

The following SQL creates a CHECK constraint on the column ‘Vendor_Name’ when the table ‘Sales’ is created in various relational databases:

MySQL:

1

2

3

4

5

6

7

8

CREATE TABLE Sales (

    Sale_Id int NOT NULL UNIQUE,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255),

    Sale_Date date,

    Profit int,

CHECK (Vendor_Name<> ’ABC’)

);

SQL Server / Oracle / MS Access:

1

2

3

4

5

6

7

CREATE TABLE Sales (

    Sale_Id int NOT NULL UNIQUE,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255) CHECK (Vendor_Name<> ’ABC’),

    Sale_Date date,

    Profit int

);

Consider now that along with the rule for the vendor ‘ABC’, the business only wants sales with a profit greater than 500 to be recorded in the ‘Sales’ table. 

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

1

2

3

4

5

6

7

8

CREATE TABLE Sales (

    Sale_Id int NOT NULL,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255),

    Sale_Date date,

    Profit int,

CONSTRAINT Chk_Sales CHECK (Vendor_Name <> ’ABC’ and Profit>500)

);

Altering a CHECK Constraint after the Creation of a Table:

To create a CHECK constraint on the ‘Vendor_Name’ column when the table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access

1

2

ALTER TABLE Sales

ADD CHECK (Vendor_Name<> ‘ABC’);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales

ADD CONSTRAINT Chk_Sales CHECK (Vendor_Name <> ’ABC’ and Profit>500)

Dropping a CHECK Constraint:

To drop a CHECK constraint, we will need to specify the naming convention that was used during the creation of the constraint:

MySQL:

1

2

ALTER TABLE Persons

DROP CHECK CHK_Sales;

SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Persons

DROP CONSTRAINT CHK_Sales;

The DEFAULT Constraint

The DEFAULT constraint is used to specify a default value that is to be entered in any record in a particular column is left blank. The default value will be added to all new records if no other value is specified.

Applying the DEFAULT Constraint:

The DEFAULT constraint can be defined either during the creation of the table or can be put in place later via an alter statement.

Declaring a DEFAULT Constraint during the Creation of a Table:

The following SQL sets a DEFAULT value for the ‘Vendor_Name’ column when the ‘Sales’ table is created:

My SQL / SQL Server / Oracle / MS Access:

1

2

3

4

5

6

7

CREATE TABLE Sales (

    Sale_Id int NOT NULL UNIQUE,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255) DEFAULT ‘Unknown Vendor’,

    Sale_Date date,

    Profit int

);

The DEFAULT constraint can also be used to populate columns with system values, for example, GETDATE().

1

2

3

4

5

6

7

CREATE TABLE Sales (

    Sale_Id int NOT NULL UNIQUE,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255),

    Sale_Date date DEFAULT GETDATE(),

    Profit int

);

Altering a DEFAULT Constraint after the Creation of a Table:

To create a DEFAULT constraint on the ‘Vendor_Name’ column when the table is already created, use the following SQL:

MySQL:

1

2

ALTER TABLE Sales

ALTER Vendor_Name SET DEFAULT 'Unknown Vendor';

SQL Server:

1

2

3

ALTER TABLE Sales

ADD CONSTRAINT df_Vendor

DEFAULT 'Unknown Vendor' FOR Vendor_Name;

MS Access:

1

2

ALTER TABLE Sales

ALTER COLUMN Vendor_Name SET DEFAULT 'Unknown Vendor';

Oracle:

1

2

ALTER TABLE Sales

MODIFY Vendor_Name DEFAULT 'Unknown Vendor';

Dropping a DEFAULT Constraint:

To drop a DEFAULT constraint, use the following SQL:

MySQL:

1

2

ALTER TABLE Sales

ALTER Vendor_Name DROP DEFAULT;

SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales

ALTER COLUMN Vendor_Name DROP DEFAULT;

The INDEX Constraint

The INDEX constraint is used to create indexes on a table in a relational database. Tables in a relational database can grow to be extremely long with a great number of rows present in each table, under the circumstances, retrieving information via SQL can sometimes be a very time taking process. By creating an index, the performance of data retrieval queries can be greatly improved. The users cannot see the indexes, they are just used by the SQL engine to speed up searches/queries.

Applying the INDEX Constraint:

We have the option of creating an INDEX that allows duplicates, or we can create a unique INDEX. Indexes can be created or dropped at any point in time and do not have to be a part of the table definition at the time of table creation.

Creating an INDEX Constraint:

Creates an INDEX on a table with duplicate values allowed:

1

2

CREATE INDEX idx_id

ON Sales (Sale_Id);

Creating aUNIQUEINDEX Constraint:

Creates a unique INDEX on a table. Duplicate values are not allowed:

1

2

CREATE UNIQUE INDEX idx_id

ON Sales (Sale_Id);

If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:

1

2

CREATE UNIQUE INDEX idx_sale

ON Sales (Sale_Id, Sale_Amount);

Dropping an INDEX Constraint:

The DROP INDEX statement is used to delete an index in a table:

MS Access:

1DROP INDEX idx_id ON Sales;

SQL Server:

1DROP INDEX Sales.idx_id;

DB2/Oracle:

1DROP INDEX idx_id;

MySQL:

1

2

ALTER TABLE Sales

DROP INDEX idx_id;

The PRIMARY KEY Constraint

PRIMARY KEYS are unique identifiers for each row present in a table. They can be values present in a single column of a table or a combination of multiple columns in the table. The PRIMARY KEY column cannot be NULL and has to be UNIQUE. The value of the PRIMARY KEY in the table is a unique identifier for a particular row in the parent table which connects the row of the table to further information available in another table (the child table), where the same unique identifier exists as a FOREIGN KEY. Every FOREIGN KEY value in the second table has to exist in the first as a PRIMARY KEY. This is how information is kept consistent in relational databases when they are broken down into multiple Fact and Dimension tables. The PRIMARY KEY – FOREIGN KEY columns are used as the join condition between two tables and the contained information in the tables are extracted.

Applying the PRIMARY KEY Constraint:

The PRIMARY KEY constraint can be defined either during the creation of the table or can be put in place later via an alter statement.

Declaring a PRIMARY KEY Constraint during the Creation of a Table:

The following SQL creates a PRIMARY KEY on the ‘Sale_Id’ column when the ‘Sales’ table is created in various relational databases:

MySQL:

1

2

3

4

5

6

7

8

CREATE TABLE Sales (

    Sale_Id int NOT NULL,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255),

    Sale_Date date,

    Profit int,

    PRIMARY KEY (Sale_Id)

);

SQL Server / Oracle / MS Access:

1

2

3

4

5

6

7

CREATE TABLE Sales (

    Sale_Id int NOT NULL PRIMARY KEY,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255),

    Sale_Date date,

    Profit int,

);

To allow naming of a PRIMARY KEY constraint and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

1

2

3

4

5

6

7

8

CREATE TABLE Sales (

    Sale_Id int NOT NULL,

    Sale_Amount int NOT NULL,

    Vendor_Name varchar(255),

    Sale_Date date,

    Profit int,

    CONSTRAINT PK_Sales PRIMARY KEY (Sale_Id, Sale_Amount)

);

Note: In the example above there is only ONE PRIMARY KEY (PK_Sales). However, the VALUE of the primary key is made up of TWO COLUMNS (Sale_Id + Sale_Amount).

Altering a PRIMARY KEY Constraint after the Creation of a Table:

To create a PRIMARY KEY constraint on the ‘Sale_Id’ column when the table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales

ADD PRIMARY KEY (Sale_Id);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales

ADD CONSTRAINT PK_ Sales PRIMARY KEY (Sale_Id,Sale_Amount);

Note: If you use ALTER TABLE to add a primary key, the primary key column(s) must have been declared to not contain NULL values (when the table was first created) and have only UNIQUE values, otherwise the SQL statement will not be executed.

Dropping a PRIMARY KEY Constraint:

To drop a PRIMARY KEY constraint, use the following SQL:

MySQL:

1

2

ALTER TABLE Sales

DROP PRIMARY KEY;

SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales

DROP CONSTRAINT PK_Sales;

The FOREIGN KEY Constraint

The foreign key constraint is used to prevent operations in a relational database that would destroy links between tables. The FOREIGN KEY is a column (or a group of columns) in one table, that refers to the PRIMARY KEY of another table. The table with the FOREIGN KEY is called the child table while the referenced table with the PRIMARY KEY is called the parent table. 

Consider the two following tables:

Sales table:

Sale_IdSale_AmountVendor_NameSale_DateProfit
123100ABC01-12-201820
234200BCD14-06-201955
345500CDE22-03-202032
456100EFG25-04-202140

Sales_Person table:

Sales_Person_IdSales_Person_NameSales_Person_LocationSale_Id
1RahulKolkata234
2SwetaMumbai456
3AtulNew Delhi123
4ShrutiMumbai345

The ‘Sale_Id’ column in the ‘Sales_person’ table refers to the ‘Sale_Id’ in the ‘Sales’ table. 

The ‘Sale_Id’ in the ‘Sales’ table is the PRIMARY KEY.

The ‘Sale_Id’ in the ‘Sales_Person’ table is the FOREIGN KEY.

Notice that every value for ‘Sale_Id’ present in the ‘Sales_Person’ table is also available in the ‘Sale_Id’ column in the ‘Sales’ table. This is so due to the PRIMARY KEY – FOREIGN KEY relationship defined between the two tables. No value for a ‘Sale_Id’ can be entered into the ‘Sales_Person’ table that does not already exist in the ‘Sales’ table. If we try to insert such a value, because of the PRIMARY KEY – FOREIGN KEY constraint, the insertion will be rejected.

Applying the FOREIGN KEY Constraint:

The FOREIGN KEY constraint can be defined either during the creation of the table or can be put in place later via an alter statement.

Declaring a FOREIGN KEY Constraint during the Creation of a Table:

The following SQL creates a FOREIGN KEY on the ‘Sale_Id’ column when the ‘Sales_Person’ table is created:

MySQL:

1

2

3

4

5

6

7

8

CREATE TABLE Sales_Person (

    Sales_Person_Id int NOT NULL,

    Sales_Person_Name varchar(255),

    Sales_Person_Location varchar(255),

    Sale_Id int NOT NULL,

    PRIMARY KEY (Sales_Person_Id),

    FOREIGN KEY (Sale_Id) REFERENCES Sales(Sale_Id)

);

SQL Server / Oracle / MS Access:

1

2

3

4

5

6

CREATE TABLE Sales_Person (

    Sales_Person_Id int NOT NULL PRIMARY KEY,

    Sales_Person_Name varchar(255),

    Sales_Person_Location varchar(255),

    Sale_Id int FOREIGN KEY REFERENCES Sales(Sale_Id)

);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

1

2

3

4

5

6

7

8

9

CREATE TABLE Sales_Person (

    Sales_Person_Id int NOT NULL,

    Sales_Person_Name varchar(255),

    Sales_Person_Location varchar(255),

    Sale_Id int NOT NULL,

    PRIMARY KEY (Sales_Person_Id),

    CONSTRAINT FK_Sales_Sales_Person FOREIGN KEY (Sale_Id)

    REFERENCES Persons Sales(Sale_Id)

);

Altering a FOREIGN KEY Constraint after the Creation of a Table:

To create a FOREIGN KEY constraint on the ‘Sale_Id’ column when the table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales_Person

ADD FOREIGN KEY (Sale_Id) REFERENCES Sales(Sale_Id);

To allow naming of a FOREIGN KEY constraint and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

1

2

3

ALTER TABLE Sales_Person

ADD CONSTRAINT FK_Sales_Sales_Person

FOREIGN KEY (Sale_Id) REFERENCES Sales(Sale_Id);

Dropping a FOREIGN KEY Constraint:

To drop a FOREIGN KEY constraint, use the following SQL:

MySQL:

1

2

ALTER TABLE Sales_Person

DROP FOREIGN KEY FK_Sales_Sales_Person;

SQL Server / Oracle / MS Access:

1

2

ALTER TABLE Sales_Person

DROP CONSTRAINT FK_Sales_Sales_Person;

Conclusion

This concludes our list of commonly used SQL constraints. Which one do you think is the most useful? Tell us all about your experience with SQL constraints in the comment section below. Happy Learning!


Original article source at: https://www.mygreatlearning.com

#SQLConstraints #sql 

What is GEEK

Buddha Community

What Are SQL Constraints? Everything You Need to Know
Cayla  Erdman

Cayla Erdman

1594369800

Introduction to Structured Query Language SQL pdf

SQL stands for Structured Query Language. SQL is a scripting language expected to store, control, and inquiry information put away in social databases. The main manifestation of SQL showed up in 1974, when a gathering in IBM built up the principal model of a social database. The primary business social database was discharged by Relational Software later turning out to be Oracle.

Models for SQL exist. In any case, the SQL that can be utilized on every last one of the major RDBMS today is in various flavors. This is because of two reasons:

1. The SQL order standard is genuinely intricate, and it isn’t handy to actualize the whole standard.

2. Every database seller needs an approach to separate its item from others.

Right now, contrasts are noted where fitting.

#programming books #beginning sql pdf #commands sql #download free sql full book pdf #introduction to sql pdf #introduction to sql ppt #introduction to sql #practical sql pdf #sql commands pdf with examples free download #sql commands #sql free bool download #sql guide #sql language #sql pdf #sql ppt #sql programming language #sql tutorial for beginners #sql tutorial pdf #sql #structured query language pdf #structured query language ppt #structured query language

Cayla  Erdman

Cayla Erdman

1596441660

Welcome Back the T-SQL Debugger with SQL Complete – SQL Debugger

When you develop large chunks of T-SQL code with the help of the SQL Server Management Studio tool, it is essential to test the “Live” behavior of your code by making sure that each small piece of code works fine and being able to allocate any error message that may cause a failure within that code.

The easiest way to perform that would be to use the T-SQL debugger feature, which used to be built-in over the SQL Server Management Studio tool. But since the T-SQL debugger feature was removed completely from SQL Server Management Studio 18 and later editions, we need a replacement for that feature. This is because we cannot keep using the old versions of SSMS just to support the T-SQL Debugger feature without “enjoying” the new features and bug fixes that are released in the new SSMS versions.

If you plan to wait for SSMS to bring back the T-SQL Debugger feature, vote in the Put Debugger back into SSMS 18 to ask Microsoft to reintroduce it.

As for me, I searched for an alternative tool for a T-SQL Debugger SSMS built-in feature and found that Devart company rolled out a new T-SQL Debugger feature to version 6.4 of SQL – Complete tool. SQL Complete is an add-in for Visual Studio and SSMS that offers scripts autocompletion capabilities, which help develop and debug your SQL database project.

The SQL Debugger feature of SQL Complete allows you to check the execution of your scripts, procedures, functions, and triggers step by step by adding breakpoints to the lines where you plan to start, suspend, evaluate, step through, and then to continue the execution of your script.

You can download SQL Complete from the dbForge Download page and install it on your machine using a straight-forward installation wizard. The wizard will ask you to specify the installation path for the SQL Complete tool and the versions of SSMS and Visual Studio that you plan to install the SQL Complete on, as an add-in, from the versions that are installed on your machine, as shown below:

Once SQL Complete is fully installed on your machine, the dbForge SQL Complete installation wizard will notify you of whether the installation was completed successfully or the wizard faced any specific issue that you can troubleshoot and fix easily. If there are no issues, the wizard will provide you with an option to open the SSMS tool and start using the SQL Complete tool, as displayed below:

When you open SSMS, you will see a new “Debug” tools menu, under which you can navigate the SQL Debugger feature options. Besides, you will see a list of icons that will be used to control the debug mode of the T-SQL query at the leftmost side of the SSMS tool. If you cannot see the list, you can go to View -> Toolbars -> Debugger to make these icons visible.

During the debugging session, the SQL Debugger icons will be as follows:

The functionality of these icons within the SQL Debugger can be summarized as:

  • Adding Breakpoints to control the execution pause of the T-SQL script at a specific statement allows you to check the debugging information of the T-SQL statements such as the values for the parameters and the variables.
  • Step Into is “navigate” through the script statements one by one, allowing you to check how each statement behaves.
  • Step Over is “execute” a specific stored procedure if you are sure that it contains no error.
  • Step Out is “return” from the stored procedure, function, or trigger to the main debugging window.
  • Continue executing the script until reaching the next breakpoint.
  • Stop Debugging is “terminate” the debugging session.
  • Restart “stop and start” the current debugging session.

#sql server #sql #sql debugger #sql server #sql server stored procedure #ssms #t-sql queries

Cayla  Erdman

Cayla Erdman

1596448980

The Easy Guide on How to Use Subqueries in SQL Server

Let’s say the chief credit and collections officer asks you to list down the names of people, their unpaid balances per month, and the current running balance and wants you to import this data array into Excel. The purpose is to analyze the data and come up with an offer making payments lighter to mitigate the effects of the COVID19 pandemic.

Do you opt to use a query and a nested subquery or a join? What decision will you make?

SQL Subqueries – What Are They?

Before we do a deep dive into syntax, performance impact, and caveats, why not define a subquery first?

In the simplest terms, a subquery is a query within a query. While a query that embodies a subquery is the outer query, we refer to a subquery as the inner query or inner select. And parentheses enclose a subquery similar to the structure below:

SELECT 
 col1
,col2
,(subquery) as col3
FROM table1
[JOIN table2 ON table1.col1 = table2.col2]
WHERE col1 <operator> (subquery)

We are going to look upon the following points in this post:

  • SQL subquery syntax depending on different subquery types and operators.
  • When and in what sort of statements one can use a subquery.
  • Performance implications vs. JOINs.
  • Common caveats when using SQL subqueries.

As is customary, we provide examples and illustrations to enhance understanding. But bear in mind that the main focus of this post is on subqueries in SQL Server.

Now, let’s get started.

Make SQL Subqueries That Are Self-Contained or Correlated

For one thing, subqueries are categorized based on their dependency on the outer query.

Let me describe what a self-contained subquery is.

Self-contained subqueries (or sometimes referred to as non-correlated or simple subqueries) are independent of the tables in the outer query. Let me illustrate this:

-- Get sales orders of customers from Southwest United States 
-- (TerritoryID = 4)

USE [AdventureWorks]
GO
SELECT CustomerID, SalesOrderID
FROM Sales.SalesOrderHeader
WHERE CustomerID IN (SELECT [CustomerID]
                     FROM [AdventureWorks].[Sales].[Customer]
                     WHERE TerritoryID = 4)

As demonstrated in the above code, the subquery (enclosed in parentheses below) has no references to any column in the outer query. Additionally, you can highlight the subquery in SQL Server Management Studio and execute it without getting any runtime errors.

Which, in turn, leads to easier debugging of self-contained subqueries.

The next thing to consider is correlated subqueries. Compared to its self-contained counterpart, this one has at least one column being referenced from the outer query. To clarify, I will provide an example:

USE [AdventureWorks]
GO
SELECT DISTINCT a.LastName, a.FirstName, b.BusinessEntityID
FROM Person.Person AS p
JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID
WHERE 1262000.00 IN
    (SELECT [SalesQuota]
    FROM Sales.SalesPersonQuotaHistory spq
    WHERE p.BusinessEntityID = spq.BusinessEntityID)

Were you attentive enough to notice the reference to BusinessEntityID from the Person table? Well done!

Once a column from the outer query is referenced in the subquery, it becomes a correlated subquery. One more point to consider: if you highlight a subquery and execute it, an error will occur.

And yes, you are absolutely right: this makes correlated subqueries pretty harder to debug.

To make debugging possible, follow these steps:

  • isolate the subquery.
  • replace the reference to the outer query with a constant value.

Isolating the subquery for debugging will make it look like this:

SELECT [SalesQuota]
    FROM Sales.SalesPersonQuotaHistory spq
    WHERE spq.BusinessEntityID = <constant value>

Now, let’s dig a little deeper into the output of subqueries.

Make SQL Subqueries With 3 Possible Returned Values

Well, first, let’s think of what returned values can we expect from SQL subqueries.

In fact, there are 3 possible outcomes:

  • A single value
  • Multiple values
  • Whole tables

Single Value

Let’s start with single-valued output. This type of subquery can appear anywhere in the outer query where an expression is expected, like the WHERE clause.

-- Output a single value which is the maximum or last TransactionID
USE [AdventureWorks]
GO
SELECT TransactionID, ProductID, TransactionDate, Quantity
FROM Production.TransactionHistory
WHERE TransactionID = (SELECT MAX(t.TransactionID) 
                       FROM Production.TransactionHistory t)

When you use a MAX() function, you retrieve a single value. That’s exactly what happened to our subquery above. Using the equal (=) operator tells SQL Server that you expect a single value. Another thing: if the subquery returns multiple values using the equals (=) operator, you get an error, similar to the one below:

Msg 512, Level 16, State 1, Line 20
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Multiple Values

Next, we examine the multi-valued output. This kind of subquery returns a list of values with a single column. Additionally, operators like IN and NOT IN will expect one or more values.

-- Output multiple values which is a list of customers with lastnames that --- start with 'I'

USE [AdventureWorks]
GO
SELECT [SalesOrderID], [OrderDate], [ShipDate], [CustomerID]
FROM Sales.SalesOrderHeader
WHERE [CustomerID] IN (SELECT c.[CustomerID] FROM Sales.Customer c
INNER JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
WHERE p.lastname LIKE N'I%' AND p.PersonType='SC')

Whole Table Values

And last but not least, why not delve into whole table outputs.

-- Output a table of values based on sales orders
USE [AdventureWorks]
GO
SELECT [ShipYear],
COUNT(DISTINCT [CustomerID]) AS CustomerCount
FROM (SELECT YEAR([ShipDate]) AS [ShipYear], [CustomerID] 
      FROM Sales.SalesOrderHeader) AS Shipments
GROUP BY [ShipYear]
ORDER BY [ShipYear]

Have you noticed the FROM clause?

Instead of using a table, it used a subquery. This is called a derived table or a table subquery.

And now, let me present you some ground rules when using this sort of query:

  • All columns in the subquery should have unique names. Much like a physical table, a derived table should have unique column names.
  • ORDER BY is not allowed unless TOP is also specified. That’s because the derived table represents a relational table where rows have no defined order.

In this case, a derived table has the benefits of a physical table. That’s why in our example, we can use COUNT() in one of the columns of the derived table.

That’s about all regarding subquery outputs. But before we get any further, you may have noticed that the logic behind the example for multiple values and others as well can also be done using a JOIN.

-- Output multiple values which is a list of customers with lastnames that start with 'I'
USE [AdventureWorks]
GO
SELECT o.[SalesOrderID], o.[OrderDate], o.[ShipDate], o.[CustomerID]
FROM Sales.SalesOrderHeader o
INNER JOIN Sales.Customer c on o.CustomerID = c.CustomerID
INNER JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
WHERE p.LastName LIKE N'I%' AND p.PersonType = 'SC'

In fact, the output will be the same. But which one performs better?

Before we get into that, let me tell you that I have dedicated a section to this hot topic. We’ll examine it with complete execution plans and have a look at illustrations.

So, bear with me for a moment. Let’s discuss another way to place your subqueries.

#sql server #sql query #sql server #sql subqueries #t-sql statements #sql

Ruth  Nabimanya

Ruth Nabimanya

1621850444

List of Available Database for Current User In SQL Server

Introduction

When working in the SQL Server, we may have to check some other databases other than the current one which we are working. In that scenario we may not be sure that does we have access to those Databases?. In this article we discuss the list of databases that are available for the current logged user in SQL Server

Get the list of database
Conclusion

#sql server #available databases for current user #check database has access #list of available database #sql #sql query #sql server database #sql tips #sql tips and tricks #tips

Introduction to Recursive CTE

This article will introduce the concept of SQL recursive. Recursive CTE is a really cool. We will see that it can often simplify our code, and avoid a cascade of SQL queries!

Why use a recursive CTE ?

The recursive queries are used to query hierarchical data. It avoids a cascade of SQL queries, you can only do one query to retrieve the hierarchical data.

What is recursive CTE ?

First, what is a CTE? A CTE (Common Table Expression) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. For example, you can use CTE when, in a query, you will use the same subquery more than once.

A recursive CTE is one having a subquery that refers to its own name!

Recursive CTE is defined in the SQL standard.

How to make a recursive CTE?

A recursive CTE has this structure:

  • The WITH clause must begin with “WITH RECURSIVE”
  • The recursive CTE subquery has two parts, separated by “UNION [ALL]” or “UNION DISTINCT”:
  • The first part produces the initial row(s) for the CTE. This SELECT does not refer to the CTE name.
  • The second part recurses by referring to the CTE name in its FROM clause.

Practice / Example

In this example, we use hierarchical data. Each row can have zero or one parent. And it parent can also have a parent etc.

Create table test (id integer, parent_id integer);

insert into test (id, parent_id) values (1, null);

insert into test (id, parent_id) values (11, 1);
insert into test (id, parent_id) values (111, 11);

insert into test (id, parent_id) values (112, 11);

insert into test (id, parent_id) values (12, 1);

insert into test (id, parent_id) values (121, 12);

For example, the row with id 111 has as ancestors: 11 and 1.

Before knowing the recursive CTE, I was doing several queries to get all the ancestors of a row.

For example, to retrieve all the ancestors of the row with id 111.

While (has parent)

	Select id, parent_id from test where id = X

With recursive CTE, we can retrieve all ancestors of a row with only one SQL query :)

WITH RECURSIVE cte_test AS (
	SELECT id, parent_id FROM test WHERE id = 111
	UNION 
	SELECT test.id, test.parent_id FROM test JOIN cte_test ON cte_test.id = test.parent_id

) SELECT * FROM cte_test

Explanations:

  • “WITH RECURSIVE”:

It indicates we will make recursive

  • “SELECT id, parent_id FROM test WHERE id = 111”:

It is the initial query.

  • “UNION … JOIN cte_test” :

It is the recursive expression! We make a jointure with the current CTE!

Replay this example here

#sql #database #sql-server #sql-injection #writing-sql-queries #sql-beginner-tips #better-sql-querying-tips #sql-top-story