{"id":19177421,"url":"https://github.com/mahadmuhammad/database-sql-server","last_synced_at":"2026-02-27T16:11:39.661Z","repository":{"id":172740545,"uuid":"601661276","full_name":"MahadMuhammad/DATABASE-SQL-SERVER","owner":"MahadMuhammad","description":"My Database repository for storing DBMS courses of university","archived":false,"fork":false,"pushed_at":"2023-06-14T06:30:57.000Z","size":24459,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-23T01:18:36.094Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TSQL","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MahadMuhammad.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-14T14:49:00.000Z","updated_at":"2024-11-20T09:27:02.000Z","dependencies_parsed_at":null,"dependency_job_id":"3bc61d85-8088-4509-8152-b6a9d58d14de","html_url":"https://github.com/MahadMuhammad/DATABASE-SQL-SERVER","commit_stats":null,"previous_names":["mahadmuhammad/database-sql-server"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/MahadMuhammad/DATABASE-SQL-SERVER","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahadMuhammad%2FDATABASE-SQL-SERVER","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahadMuhammad%2FDATABASE-SQL-SERVER/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahadMuhammad%2FDATABASE-SQL-SERVER/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahadMuhammad%2FDATABASE-SQL-SERVER/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MahadMuhammad","download_url":"https://codeload.github.com/MahadMuhammad/DATABASE-SQL-SERVER/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahadMuhammad%2FDATABASE-SQL-SERVER/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29903618,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-27T14:46:13.553Z","status":"ssl_error","status_checked_at":"2026-02-27T14:46:10.522Z","response_time":57,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T10:33:29.452Z","updated_at":"2026-02-27T16:11:39.627Z","avatar_url":"https://github.com/MahadMuhammad.png","language":"TSQL","funding_links":[],"categories":[],"sub_categories":[],"readme":"# DATABASE-SQL-SERVER\nMy Database repository for storing DBMS courses of university\n\n***To create a Table***\n```sql\n\tcreate table risk_clos_rank(\n\t\tid_num int IDENTITY(1,1) NOT NULL,\n\t    username nvarchar(100),\n\t    datetime_of_decision DATETIME\n\t);\n\t\n\tCREATE TABLE TheNameOfYourTable (\n\t  ID INT NOT NULL IDENTITY(1,1),\n\t  DateAdded DATETIME DEFAULT(getdate()) NOT NULL,\n\t  Description VARCHAR(100) NULL,\n\t  IsGood BIT DEFAULT(0) NOT NULL,\n\t  TotalPrice MONEY NOT NULL,  \n\t  CategoryID int NOT NULL REFERENCES Categories(ID),\n\t  PRIMARY KEY (ID)\n\t);\n```\n***To create a copy of table( doesnt create constraints like primary key, not null , indexes ect)***\n```sql\n\tSELECT * INTO NewTable FROM OldTable\n    Eg. SELECT * INTO clos_ext_bkup FROM clos_ext;\n```\n***To create a copy of table with its data (create and insert)***\n```sql\n\tSELECT expressions INTO new_table FROM tables [WHERE conditions];\n\tSELECT employee_id AS contact_id, last_name, first_name INTO contacts FROM employees WHERE employee_id \u003c 1000;\n```\n\nThe format of new_table is determined by evaluating the expressions in the select list. The columns in new_table are created in the order specified by the select list. Each column in new_table has the same name, data type, nullability, and value as the corresponding expression in the select list.\n\n***Inserting Data from another table ( only insert)***\n```sql\n\tINSERT INTO Table (col1, col2, col3) SELECT col1, col2, col3  FROM other_table WHERE sql = 'cool'\t\n\tINSERT INTO contacts (contact_id, last_name, first_name) SELECT employee_id, last_name, first_name FROM employees WHERE employee_id \u003c= 100;\n```\t\n***Inserting Multiple values***\n```sql\n\tINSERT INTO table1 (First, Last)\n\tVALUES\n\t\t('Fred', 'Smith'),\n\t\t('John', 'Smith'),\n\t\t('Michael', 'Smith'),\n\t\t('Robert', 'Smith');\n```\t\n***To add a column***\n```sql\n\tALTER TABLE table_name  ADD column_1 column-definition,column_2 column-definition,column_n column_definition;\n\talter table risk_user_approval_tree add lineusr nvarchar(100);\n\tALTER TABLE table ADD columnname BIT CONSTRAINT Constraint_name DEFAULT 0 WITH VALUES\n```\n***To add a auto increment***\n```\n\tALTER TABLE 'tableName' ADD 'NewColumn' INT IDENTITY(1,1);\n```\n***To add a column with computed value***\n```sql\n\tALTER TABLE dbo.Products ADD RetailValue AS (QtyAvailable * UnitPrice * 1.5);\n```\n***To delete/drop a column***\n```sql\n\tALTER TABLE table_name DROP COLUMN column_name;\n```\n***To drop a table***\n```sql\n\tDROP TABLE tablename;\n```\t\n***To modify a column***\n```sql\n\tALTER TABLE table_name ALTER COLUMN column_name column_type;\n```\t\n***To update a row***\n```sql\n\tUPDATE clos_customer_master SET Prev = 'Reactivation' WHERE Prev = 'Reactivate';\n```\n\n***To update a row from select clause***\n```sql\n\tUPDATE table SET Col1 = i.Col1, Col2 = i.Col2 FROM ( SELECT ID, Col1, Col2 FROM other_table) i WHERE i.ID = table.ID;\n```\nThe subquery results are substituted into the outer query. As we need table object in outer query, we need to make an alias of inner query.\n\t\n***To add a primary key***\n```sql\n\tALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n);\n```\n***To find the name of constraints***\n```sql\n\tSELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'tablename'\n```\n***To find name of Primary key constraint***\n```sql\n\tSELECT name FROM sys.key_constraints  WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = N'CLOS_ext';  \t\n```\t\n***Drop primary key***\n```sql\n\tALTER TABLE table_name DROP CONSTRAINT constraint_name;\n```\t\n***To rename a column (alter command doesnt work here)***\n```sql\n\tsp_rename 'table_name.old_column_name', 'new_column_name', 'COLUMN';\n\tsp_rename 'cl_ff_docm.WINAME', 'WI_NAME', 'COLUMN';\n```\n***To rename a table***\n```sql\n\tsp_rename 'old_table_name', 'new_table_name';\n```\t\n***To top 10% of records***\n```sql\n\tSELECT TOP(10) * FROM CLOS_EXT\n```\t\n***To find when a table was altered***\n```sql\n\tSELECT [name] , create_date, modify_date FROM sys.tables;\n```\n***To find which table contains a given column***\n```sql\n\tSELECT * FROM INFORMATION_SCHEMA.COLUMNS;\n\t\n\tSELECT OBJECT_SCHEMA_NAME (c.object_id) SchemaName,\n\t\t\to.Name AS Table_Name, \n\t\t\tc.Name AS Field_Name,\n\t\t\tt.Name AS Data_Type,\n\t\t\tt.max_length AS Length_Size,\n\t\t\tt.precision AS Precision\n\tFROM sys.columns c \n\t\t INNER JOIN sys.objects o ON o.object_id = c.object_id\n\t\t LEFT JOIN  sys.types t on t.user_type_id  = c.user_type_id   \n\tWHERE o.type = 'U'\n\t-- and o.Name = 'YourTableName'\n\tORDER BY o.Name, c.Name\n```\n***To find which table has which constraint and on which column.***\n```sql\n\tSelect * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE;\n```\t\n***Selcting based on case*** \n```sql\n\tSELECT CASE \n    \t\tWHEN \u003ctest\u003e      THEN \u003creturnvalue\u003e\n            WHEN \u003cothertest\u003e THEN \u003creturnthis\u003e\n            ELSE \u003creturndefaultcase\u003e\n       END AS \u003cnewcolumnname\u003e\n\tFROM \u003ctable\u003e\n\t\n    Eg.\n\tSELECT   ProductNumber, Name, \"Price Range\" =   \n\t\t  CASE   \n\t\t\t WHEN ListPrice =  0 THEN 'Mfg item - not for resale'  \n\t\t\t WHEN ListPrice \u003c 50 THEN 'Under $50'  \n\t\t\t WHEN ListPrice \u003e= 50 and ListPrice \u003c 250 THEN 'Under $250'  \n\t\t\t WHEN ListPrice \u003e= 250 and ListPrice \u003c 1000 THEN 'Under $1000'  \n\t\t\t ELSE 'Over $1000'  \n\t\t  END  \n\tFROM Production.Product  \n\tORDER BY ProductNumber ;  \n```\n***Adding row numbers to the result***   //here we are creating \n```sql\n\tSELECT ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#, name, \n    \t\trecovery_model_desc\n\t\tFROM sys.databases \n\t\tWHERE database_id \u003c 5;\n```\n***While Loop***\n```sql\n\tDECLARE @MaxCount INTEGER\n\tDECLARE @Count INTEGER\n\tDECLARE @Txt VARCHAR(MAX)\n\tSET @Count = 1\n\tSET @Txt = ''\n\tSET @MaxCount = (SELECT MAX(RowID) FROM ConcatenationDemo) \n\tWHILE @Count\u003c=@MaxCount\n\t\tBEGIN\n\t\tIF @Txt!=''\n\t\t\tSET @Txt=@Txt+',' + (SELECT Txt FROM ConcatenationDemo \n            WHERE RowID=@Count)\n\t\tELSE\n\t\t\tSET @Txt=(SELECT Txt FROM ConcatenationDemo WHERE RowID=@Count)\n\t\tSET @Count += 1\n\t\tEND\n\tSELECT @Txt AS Txt\n\n\tDECLARE @i int\n\tSET @i = 0\n\tWHILE (@i \u003c 10)\n\tBEGIN\n\t\tSET @i = @i + 1\n\t\tPRINT @i\n\t\tIF (@i \u003e= 10)\n\t\t\tBREAK\n\t\tELSE\n\t\t\tCONTINUE\n\tEND\n```\t\n***Try / Catch Statements***\n```sql\n\tBEGIN TRY\n\t\t-- try / catch requires SQLServer 2005 \n\t\t-- run your code here\n\tEND TRY\n\tBEGIN CATCH\n\t\tPRINT 'Error Number: ' + str(error_number()) \n\t\tPRINT 'Line Number: ' + str(error_line())\n\t\tPRINT error_message()\n\t\t-- handle error condition\n\tEND CATCH\n```\t\n***To get date in DD/MM/YYYY format***\n```sql\n\tSELECT CONVERT(varchar, GETDATE(), 103);\n```\n***To get all foreign keys refrencing a given table***\n```sql\n\tEXEC sp_fkeys 'TableName'\n```\n***To get datatype, size of columns of a table***\n```sql\n\tEXEC sp_columns CLOS_EXT;\n```\t\n***To get empty string after concatenation of a string with NULL***\t\n\nWhen ***SET CONCAT_NULL_YIELDS_NULL*** is ON, concatenating a null value with a string yields a NULL result. \n\nFor example, SELECT 'abc' + NULL yields NULL. \n\nWhen SET CONCAT_NULL_YIELDS_NULL is OFF, concatenating a null value with a string yields the string itself (the null value is treated as an empty string). \n\nFor example, SELECT 'abc' + NULL yields abc.\n\n***To compile without executing***\n```sql\n\tSET NOEXEC ON;  \t\n```\nWhen SET NOEXEC is ON, SQL Server compiles each batch of Transact-SQL statements but does not execute them. \n\t\n***Updating data from another table***\n```sql\n\tUPDATE table  SET Col1 = i.Col1, Col2 = i.Col2 FROM ( SELECT ID, Col1, Col2 FROM other_table) i WHERE i.ID = table.ID\n```\n***Check if column exists in table***\n```sql\n\tIF EXISTS(SELECT 1 FROM sys.columns \n\t\t\t  WHERE Name = N'columnName'\n\t\t\t  AND Object_ID = Object_ID(N'schemaName.tableName'))\n\tBEGIN\n\t\t-- Column Exists\n\tEND\n```\n***Converting Multi row data into a comma separated string***\n```sql\n\tDECLARE @Names VARCHAR(8000) \n\tSELECT @Names = COALESCE(@Names + ', ', '') + \n\t\tISNULL(Name, 'N/A')\n\tFROM People\n```\t\n***Nvarchar***\nallows storing of unicode data\n\n***To remove duplicate rows***\n```sql\n\tselect  distinct * into t2 from t1;\n\tdelete from t1;\n\tinsert into t1 select *  from t2;\n\tdrop table t2;\n```\n***Check if the table exists***\n```sql\n\tIF (EXISTS (\n\t  SELECT * \n      FROM INFORMATION_SCHEMA.TABLES \n      WHERE TABLE_SCHEMA = 'TheSchema' \n      AND  TABLE_NAME = 'TheTable')\n      )\n\tBEGIN\n\t\t--Do Stuff\n\tEND\n```\n***Find tables with given column name***\n```sql\n\tselect * from INFORMATION_SCHEMA.COLUMNS \n\twhere COLUMN_NAME like '%clientid%' \n\torder by TABLE_NAME\n```\n***Find all user tables***\n```sql\n\tSELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'\n```\n***Allows explicit values to be inserted into the identity column of a table.***\n```sql\n\tSET IDENTITY_INSERT dbo.Tool ON    \n```\nThe ***DBCC CHECKIDENT*** management command is used to reset identity counter. Example:\n```sql\n\tDBCC CHECKIDENT ('[TestTable]', RESEED, 0);\n\tGO\n```\n\n***DECLARE and SET Varibales***\n```sql\n\tDECLARE @Mojo int\n\tSET @Mojo = 1\n\tSELECT @Mojo = Column FROM Table WHERE id=1;\n```\n***Add a Foreign Key***\n```sql\n\tALTER TABLE Products WITH CHECK ADD CONSTRAINT [FK_Prod_Man] FOREIGN KEY(ManufacturerID) REFERENCES Manufacturers (ID);\n```\n***Add a NULL Constraint***\n```sql\n\tALTER TABLE TableName ALTER COLUMN ColumnName int NOT NULL;\n```\n***Set Default Value for Column***\n```sql\n\tALTER TABLE TableName ADD CONSTRAINT DF_TableName_ColumnName DEFAULT 0 FOR ColumnName;\n```\n***Create an Index***\n```sql\n\tCREATE INDEX IX_Index_Name ON Table(Columns)\n```\n***Check Constraint***\n```sql\n\tALTER TABLE TableName ADD CONSTRAINT CK_CheckName CHECK (ColumnValue \u003e 1)\t\n```\n***Single Line Comments***\n```sql\n\tSET @mojo = 1 --THIS IS A COMMENT\n```\n***Multi-Line Comments***\n```sql\n\t/* This is a comment\n\t\tthat can span\n\t\tmultiple lines\n\t*/\t\n```\n***User Defined Function***\n```\n\tCREATE FUNCTION dbo.DoStuff(@ID int)\n\tRETURNS int\n\tAS\n\tBEGIN\n\t  DECLARE @result int\n\t  IF @ID = 0\n\t\tBEGIN\n\t\t\tRETURN 0\n\t\tEND\n\t  SELECT @result = COUNT(*) \n\t  FROM table WHERE ID = @ID\n\t  RETURN @result\n\tEND\n\tGO\n\tSELECT dbo.DoStuff(0);\t\n```\t\n***Pivot - To convert rows into columns***\n```sql\n\tSELECT Wi_name, Often, Sometimes, Never, NA\n\tFROM\n    (\n        SELECT  Wi_name, Past_due, 'Selected' T, '' F\n        FROM NG_CA_MISCELLANEOUS_DETAILS\n    ) P1\n    PIVOT\n    ( \n         MAX(T) for Past_due IN ([Often], [Sometimes], [Never],[NA])\n    )\n    P2 ORDER BY WI_NAME;\n```    \n\n***WITH (NOLOCK)***\n\nis the equivalent of using READ UNCOMMITED as a transaction isolation level. While it can prevent reads being deadlocked by other. \n\n### ***Finding the last identity inserted into a table***\n\n- ***@@IDENTITY*** returns the last identity value generated for any table in the current session, across all scopes. You need to be careful here, since it's across scopes. You could get a value from a trigger, instead of your current statement.\n\n- ***SCOPE_IDENTITY()*** returns the last identity value generated for any table in the current session and the current scope. Generally what you want to use.\n\n- ***IDENT_CURRENT('tableName')*** returns the last identity value generated for a specific table in any session and any scope. This lets you specify which table you want the value from, in case the two above aren't quite what you need (very rare). You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into.\n\n@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. \n\nHowever, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope. That is, if there was a second IDENTITY inserted based on a trigger after your insert, it would not be reflected in SCOPE_IDENTITY, only the insert you performed.\n\n\nIDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.\n\nIdentity doesn’t guarantee uniqueness. If you want that, make a PK or add a unique index.\n\n### Trigger\n```SQL\nCREATE TRIGGER TrackRetiredProducts\nON Products\nAFTER DELETE\nAS\nINSERT INTO RetiredProducts (Product, Measure)\nSELECT Product, Measure\nFROM deleted;\n```\n### Stored Procedure CREATE\n```SQL\nCREATE PROCEDURE dbo.uspGetAddress @City nvarchar(30)\nAS\nSELECT * FROM Person.Address WHERE City = @City\n```\n### Stored Procedure EXECUTE\n```SQL\nDeclare @ReturnValue as int\nDeclare @RowCount as int\nEXEC @ReturnValue =\ndbo.cusp_\nTripSummaryDelete\n@TripDate = '1/5/2017',\n@RowCountOut = @RowCount OUTPUT\nSelect @ReturnValue as ReturnValue,\n@RowCount as RowCount\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmahadmuhammad%2Fdatabase-sql-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmahadmuhammad%2Fdatabase-sql-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmahadmuhammad%2Fdatabase-sql-server/lists"}