Removing Constraints with SQL DROP Constraint, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 10.2 Free with a free account

Removing Constraints with SQL DROP Constraint

Database Programming · Chapter 10: Table Cleanup and Structural ChangesSection 10.2 · lesson 61 of 769 min · free with a free account

← Dropping Columns and Rows from TablesNext lesson: Removing Permanent and Temporary Tables with SQL DROP →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Find, drop and restore constraints safely in MySQL, SQL Server and SQLite.

  • Explain what each constraint type enforces and what removing it allows
  • Write the MySQL and SQL Server statements that drop each type of constraint
  • Find constraint names in the catalog and remove dependent constraints in order
  • Restore a constraint after correcting the rows that would violate it

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,005 words). Read along, or search it.

Opening Scenario

An Import Blocked by a Uniqueness Rule

Amina Diallo, Lantern Books' database administrator, is asked to remove a rule that rejects duplicate contact emails during an import. The request sounds smaller than deleting data. Existing rows can remain untouched, while the database starts accepting records that used to be rejected. Which protection disappears, what depends on it, and how will Amina put the rule back after the import?

Definitions

Five Kinds of Enforced Data Rules

A constraint is an enforced data rule. A primary key identifies each row; a foreign key links a child to a valid parent key. Unique prevents repeated non-null key values. Check rejects a false condition, such as a nonpositive quantity; null can yield unknown, so required values need not null. A default supplies a value when a column is omitted. Removing a default changes that fallback; it does not rewrite previously stored values.

Sandbox Setup

Contact Emails Under a Unique Index

Our disposable customer projection preserves canonical identifiers and first names. Contact emails are illustrative extensions, and a unique index protects them. In SQLite, this explicitly created unique index enforces uniqueness. A table-declared unique constraint has an internal index that cannot be dropped independently. Run the setup. The three initial emails satisfy the rule, so creating the index succeeds quietly.

Worked Example

Dropping the Index Lets Duplicates In

Drop the explicitly created unique index, then assign Chen the same contact email as Asha. This is deliberately bad import data. Removing the protection alone does not remove customers or columns. The following update demonstrates what the unprotected table now permits. Run the file. Compare the identifiers and emails, rather than assuming successful execution means the business data is valid. All three customer rows remain. The repeated address shows why restoring uniqueness now requires cleaning the data first.

MySQL Syntax

Type-Specific Drops in MySQL

These MySQL listings remove different protections. Drop check removes the condition; alter column drop default removes the column's unnamed fallback. Drop index removes a unique index. Drop foreign key removes the relationship rule, while its supporting index can remain and need separate review. Drop primary key removes the table's primary key, which MySQL names primary. Dependencies can block the operation, even when the syntax is correct.

SQL Server Syntax

DROP CONSTRAINT With the Exact Name

SQL Server uses drop constraint with the exact name for checks, defaults, unique rules, foreign keys, and primary keys. Its optional if exists clause is available from twenty sixteen. It suppresses an absent-name error, without checking that a present constraint is the intended target. Dropping a default can leave an omitted nullable value null. For a required column, an insert may fail instead of receiving a fallback.

Combined Removals

Removing Several Rules in One Statement

Both servers can combine removals. MySQL separates typed actions with commas; SQL Server lists names after drop constraint. MySQL also offers general drop constraint syntax from version eight point zero point nineteen, for supported named constraints. That general form does not replace the column-default operation. Constraint namespaces can also make a shared name ambiguous, so type-specific forms communicate intent clearly.

Finding Names

Look Up Constraint Names in the Catalog

Find names in the database catalog. MySQL's information schema lists table constraints; show create table also exposes the complete table definition. SQL Server's system objects identify names and types. Dedicated foreign key, check, default, and key constraint views provide more focused queries. Generated names can differ across database copies. Choose meaningful names when creating rules, but query actual metadata before changing a deployed table.

Removal Order

Child Foreign Keys Go First

A foreign key on orders depends on a candidate key in customers. Remove the child's foreign key before removing the parent's referenced key. The same principle applies to referenced unique keys and parent tables. If the child table must stay, remove its relationship rule while retaining the child records. For a SQL Server column with dependent constraints, remove those constraints first. Replacing a primary key also requires resolving the existing key and all inbound dependencies.

Second Setup

A Positive Quantity Check on Order Items

Now isolate the quantity rule in a disposable projection of two canonical order items. Their quantities are positive, and the compound key prevents repeated product lines. The named check requires a positive quantity. Not null separately prevents an unknown quantity from slipping through the check's null semantics. Run this setup. SQLite version three point forty-three does not support the servers' drop constraint statement; a schema rebuild can express the change.

SQLite Workaround

Rebuild the Table Without the Check

Rebuild this isolated table without the check, preserving its other declarations and copying the rows. The original table is replaced within a transaction. A general migration also preserves indexes, triggers, views, and foreign key relationships. Our isolated projection has none of those additional dependencies. Run the replacement and a deliberately invalid update. The final query will locate values that would block normal restoration of the positive-quantity check. The zero quantity is the problem. Ordinary enforced constraint restoration validates existing rows; correct the violation before putting the rule back.

Restoring the Rule

Fix the Data, Then Recreate the Index

Return to Amina's import. Correct Chen's illustrative email, then recreate the unique index over the existing customers. This creation checks the stored addresses. If duplicates remained, it would fail rather than silently accepting an inconsistent unique index. Run the repair. Protection returns after the data is made compatible, without deleting any customer row. The result still counts three customers. Amina has restored the intended rule, and the customer identities remain available to other records.

Quick Check

Inserting NULL Into a Checked Column

Consider a fresh scratch table with a positive-quantity check on one column. The script inserts a null and classifies the stored value. What happens when SQLite runs it? Choose an insert error, reported present, or reported missing. Pause, and predict.

Answer Explained

NULL Passes a Positive-Value Check

The query reports missing. Run the script: the inserted null makes the comparison unknown, which this check does not reject. The deciding declaration lacks not null. A positive-value check does not manufacture a quantity, and it does not make the field required. An error would require an additional rule rejecting null here. A present value would require an actual non-null input or a different transformation.

Key Takeaways

A Temporary Exception Needs a Tested End

Amina now knows what an import would give up: a specific validation rule, while existing rows remain available for inspection. Save the definition, discover the exact name, and remove dependencies in order. Verify the catalog after the change, rather than trusting a silent command. Finally, clean imported data and restore the intended enforced rule. A temporary exception needs a tested end, not an open-ended promise.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Removing Constraints with SQL DROP Constraint

How do you drop a constraint in SQL Server?
Use ALTER TABLE with DROP CONSTRAINT and the constraint's exact name, for example ALTER TABLE order_items DROP CONSTRAINT ck_quantity_positive; The same form removes check, default, unique, foreign key and primary key constraints. Look up the name first in catalog views such as sys.check_constraints or sys.foreign_keys, because generated names can differ between copies of a database. Since SQL Server 2016, IF EXISTS avoids an error for a missing name, but it cannot confirm you chose the right one.
How do you drop a foreign key, primary key or check constraint in MySQL?
MySQL uses type-specific clauses of ALTER TABLE: DROP FOREIGN KEY fk_name for a relationship, DROP PRIMARY KEY for the primary key, DROP INDEX for a unique index, DROP CHECK for a check constraint, and ALTER COLUMN city DROP DEFAULT for a default. Dropping a foreign key can leave its supporting index in place, so review that index separately. From MySQL 8.0.19, a general DROP CONSTRAINT form also works for named constraints.
Why can't you drop a primary key that a foreign key references?
The child table's foreign key depends on that key, so the database blocks the drop while the relationship exists. Drop the child's foreign key first, with DROP FOREIGN KEY in MySQL or DROP CONSTRAINT in SQL Server, then drop or replace the parent key. Removing the relationship rule keeps the child rows; only the enforcement disappears. In SQL Server, a column with dependent constraints likewise needs those constraints removed before the column itself can be dropped.
Why does re-adding a dropped constraint sometimes fail?
It usually fails because rows written while the rule was absent now violate it. Creating a unique index checks every stored value, so two customers sharing an email block it, and an enforced CHECK (quantity > 0) is rejected while a zero quantity exists. Find and correct the violating rows, then recreate the rule. Note that a CHECK alone accepts NULL, because a comparison with NULL is unknown rather than false, so required columns also need NOT NULL.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →