SQL UNIQUE Constraint - W3Schools

文章推薦指數: 80 %
投票人數:10人

Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a ... Tutorials References Exercises VideosNEW Menu Login PaidCourses WebsiteNEW HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C++ C# R React Kotlin    Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz XMLQuiz CyberSecurityQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate jQueryCertificate JavaCertificate C++Certificate ReactCertificate XMLCertificate × Tutorials References Exercises PaidCourses Spaces Videos Shop SQLTutorial SQLHOME SQLIntro SQLSyntax SQLSelect SQLSelectDistinct SQLWhere SQLAnd,Or,Not SQLOrderBy SQLInsertInto SQLNullValues SQLUpdate SQLDelete SQLSelectTop SQLMinandMax SQLCount,Avg,Sum SQLLike SQLWildcards SQLIn SQLBetween SQLAliases SQLJoins SQLInnerJoin SQLLeftJoin SQLRightJoin SQLFullJoin SQLSelfJoin SQLUnion SQLGroupBy SQLHaving SQLExists SQLAny,All SQLSelectInto SQLInsertIntoSelect SQLCase SQLNullFunctions SQLStoredProcedures SQLComments SQLOperators SQLDatabase SQLCreateDB SQLDropDB SQLBackupDB SQLCreateTable SQLDropTable SQLAlterTable SQLConstraints SQLNotNull SQLUnique SQLPrimaryKey SQLForeignKey SQLCheck SQLDefault SQLIndex SQLAutoIncrement SQLDates SQLViews SQLInjection SQLHosting SQLDataTypes SQLReferences SQLKeywords ADD ADDCONSTRAINT ALL ALTER ALTERCOLUMN ALTERTABLE AND ANY AS ASC BACKUPDATABASE BETWEEN CASE CHECK COLUMN CONSTRAINT CREATE CREATEDATABASE CREATEINDEX CREATEORREPLACEVIEW CREATETABLE CREATEPROCEDURE CREATEUNIQUEINDEX CREATEVIEW DATABASE DEFAULT DELETE DESC DISTINCT DROP DROPCOLUMN DROPCONSTRAINT DROPDATABASE DROPDEFAULT DROPINDEX DROPTABLE DROPVIEW EXEC EXISTS FOREIGNKEY FROM FULLOUTERJOIN GROUPBY HAVING IN INDEX INNERJOIN INSERTINTO INSERTINTOSELECT ISNULL ISNOTNULL JOIN LEFTJOIN LIKE LIMIT NOT NOTNULL OR ORDERBY OUTERJOIN PRIMARYKEY PROCEDURE RIGHTJOIN ROWNUM SELECT SELECTDISTINCT SELECTINTO SELECTTOP SET TABLE TOP TRUNCATETABLE UNION UNIONALL UNIQUE UPDATE VALUES VIEW WHERE MySQLFunctions StringFunctions: ASCII CHAR_LENGTH CHARACTER_LENGTH CONCAT CONCAT_WS FIELD FIND_IN_SET FORMAT INSERT INSTR LCASE LEFT LENGTH LOCATE LOWER LPAD LTRIM MID POSITION REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPACE STRCMP SUBSTR SUBSTRING SUBSTRING_INDEX TRIM UCASE UPPER NumericFunctions: ABS ACOS ASIN ATAN ATAN2 AVG CEIL CEILING COS COT COUNT DEGREES DIV EXP FLOOR GREATEST LEAST LN LOG LOG10 LOG2 MAX MIN MOD PI POW POWER RADIANS RAND ROUND SIGN SIN SQRT SUM TAN TRUNCATE DateFunctions: ADDDATE ADDTIME CURDATE CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURTIME DATE DATEDIFF DATE_ADD DATE_FORMAT DATE_SUB DAY DAYNAME DAYOFMONTH DAYOFWEEK DAYOFYEAR EXTRACT FROM_DAYS HOUR LAST_DAY LOCALTIME LOCALTIMESTAMP MAKEDATE MAKETIME MICROSECOND MINUTE MONTH MONTHNAME NOW PERIOD_ADD PERIOD_DIFF QUARTER SECOND SEC_TO_TIME STR_TO_DATE SUBDATE SUBTIME SYSDATE TIME TIME_FORMAT TIME_TO_SEC TIMEDIFF TIMESTAMP TO_DAYS WEEK WEEKDAY WEEKOFYEAR YEAR YEARWEEK AdvancedFunctions: BIN BINARY CASE CAST COALESCE CONNECTION_ID CONV CONVERT CURRENT_USER DATABASE IF IFNULL ISNULL LAST_INSERT_ID NULLIF SESSION_USER SYSTEM_USER USER VERSION SQLServerFunctions StringFunctions: ASCII CHAR CHARINDEX CONCAT Concatwith+ CONCAT_WS DATALENGTH DIFFERENCE FORMAT LEFT LEN LOWER LTRIM NCHAR PATINDEX QUOTENAME REPLACE REPLICATE REVERSE RIGHT RTRIM SOUNDEX SPACE STR STUFF SUBSTRING TRANSLATE TRIM UNICODE UPPER NumericFunctions: ABS ACOS ASIN ATAN ATN2 AVG CEILING COUNT COS COT DEGREES EXP FLOOR LOG LOG10 MAX MIN PI POWER RADIANS RAND ROUND SIGN SIN SQRT SQUARE SUM TAN DateFunctions: CURRENT_TIMESTAMP DATEADD DATEDIFF DATEFROMPARTS DATENAME DATEPART DAY GETDATE GETUTCDATE ISDATE MONTH SYSDATETIME YEAR AdvancedFunctions CAST COALESCE CONVERT CURRENT_USER IIF ISNULL ISNUMERIC NULLIF SESSION_USER SESSIONPROPERTY SYSTEM_USER USER_NAME MSAccessFunctions StringFunctions: Asc Chr Concatwith& CurDir Format InStr InstrRev LCase Left Len LTrim Mid Replace Right RTrim Space Split Str StrComp StrConv StrReverse Trim UCase NumericFunctions: Abs Atn Avg Cos Count Exp Fix Format Int Max Min Randomize Rnd Round Sgn Sqr Sum Val DateFunctions: Date DateAdd DateDiff DatePart DateSerial DateValue Day Format Hour Minute Month MonthName Now Second Time TimeSerial TimeValue Weekday WeekdayName Year OtherFunctions: CurrentUser Environ IsDate IsNull IsNumeric SQLQuickRef SQLExamples SQLExamples SQLQuiz SQLExercises SQLCertificate SQLUNIQUEConstraint ❮Previous Next❯ SQLUNIQUEConstraint TheUNIQUEconstraintensuresthatallvaluesinacolumnaredifferent. BoththeUNIQUEand PRIMARYKEYconstraintsprovideaguaranteeforuniquenessforacolumnorsetofcolumns. APRIMARYKEYconstraintautomaticallyhasa UNIQUEconstraint. However,youcanhavemanyUNIQUEconstraintspertable,butonlyone PRIMARYKEYconstraintpertable. SQLUNIQUEConstraintonCREATETABLE ThefollowingSQLcreatesaUNIQUEconstraintonthe"ID"columnwhenthe"Persons"tableiscreated: SQLServer/Oracle/MSAccess: CREATETABLEPersons (    IDintNOTNULLUNIQUE,     LastNamevarchar(255)NOTNULL,     FirstNamevarchar(255),     Ageint ); MySQL: CREATETABLEPersons (    IDintNOTNULL,     LastNamevarchar(255)NOTNULL,     FirstNamevarchar(255),     Ageint,     UNIQUE(ID) ); TonameaUNIQUEconstraint,andtodefinea UNIQUEconstraintonmultiplecolumns,usethefollowingSQLsyntax: MySQL/SQLServer/Oracle/MSAccess: CREATETABLEPersons (    IDintNOTNULL,     LastNamevarchar(255)NOTNULL,     FirstNamevarchar(255),     Ageint,     CONSTRAINTUC_PersonUNIQUE(ID,LastName) ); SQLUNIQUEConstraintonALTERTABLE TocreateaUNIQUEconstraintonthe"ID"columnwhenthetableisalreadycreated,usethefollowingSQL: MySQL/SQLServer/Oracle/MSAccess: ALTERTABLEPersons ADDUNIQUE(ID); TonameaUNIQUEconstraint,andtodefinea UNIQUEconstraintonmultiplecolumns,usethefollowingSQLsyntax: MySQL/SQLServer/Oracle/MSAccess: ALTERTABLEPersons ADDCONSTRAINTUC_PersonUNIQUE(ID,LastName); DROPaUNIQUEConstraint TodropaUNIQUEconstraint,usethefollowingSQL: MySQL: ALTERTABLEPersons DROPINDEXUC_Person; SQLServer/Oracle/MSAccess: ALTERTABLEPersons DROPCONSTRAINTUC_Person; ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame



請為這篇文章評分?