Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
This seems like it should be a classic invoice-item problem that has already been solved but maybe I'm not using the right words in my searches. I am running a query like this (this is just a simple example, my real query is much more complex but it returns the same results): ``` select invoice.inv_num, item.name, it...
You can use the oracle rank or row\_number analytic functions (depending on how you want to deal with duplicates/euqally ranked items). Here's how you would add a 4th column item\_number to your query : ``` select invoice.inv_num, item.name, item.qty , row_number() over (partition by inv_num order by qty desc)...
``` select invoice.inv_num, item.name, item.qty, row_number() OVER(PARTITION BY invoice.inv_num order by item.qty desc) as item_num from invoice invoice, item where invoice.inv_num = item.inv_num order by invoice.inv_num ``` `row_number()` generates Number starting with 1.. And we restart the ...
How do I generate line item numbers in an oracle sql query
[ "", "sql", "oracle", "" ]
I initially thought this would be fairly simple but for some reason I'm struggling with it. If I have a table that looks like this: ``` table1 Date ID Quantity 2/21 1 100 2/21 2 500 2/21 3 200 2/20 2 600 2/20 3 400 2/20 5 ...
This may help u,,,,, ``` SELECT ISNULL(T.ID,T1.ID), ISNULL(T.DATE,GETDATE()) AS 'CurrDate', ISNULL(T.Quantity,0) AS 'CurrQty', ISNULL(T1.DATE,GETDATE()-1) AS 'PrevDate' , ISNULL(T1.Quantity,0) AS 'PrevQty' FROM ( SELECT T.ID, T.Quantity, T...
``` SELECT curr.ID, ISNULL(Prev.date, DATEADD(DD, -1, curr.Date)) AS Prev_Date, ISNULL(prev.Quantity, 0) AS Prev_Quantity, ISNULL(curr.date, DATEADD(DD, 1, prev.Date)) AS Curr_Date, ISNULL(curr.Quantity, 0) AS Curr_Quantity FROM table1 curr FULL OUTER JOIN table1 prev ...
SQL Best way to JOIN day over day data into same row including new and deleted IDs
[ "", "sql", "sql-server", "sql-server-2008", "" ]
How can I get the columns, which an index of a table uses, in DB2? I tried: ``` DESCRIBE INDEXES FOR TABLE 'MYTABLE' SHOW DETAIL; ``` But I get the error message > ILLEGAL SYMBOL "INDEXES". SOME SYMBOLS THAT MIGHT BE LEGAL ARE: PROCEDURE PROC. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.16.53 Ideally I want information...
You can use this query to show the indexes and their columns of your tables: ``` SELECT IX.tbname, KEY.ixname, KEY.colname FROM sysibm.syskeys KEY JOIN sysibm.sysindexes IX ON KEY.ixname = IX.name WHERE IX.tbname IN ( 'SOMETABLE', 'ANOTHERTABLE' ) ORDER BY IX.tbname, ...
``` SELECT * FROM SYSIBM.SYSKEYS WHERE IXNAME IN (SELECT NAME FROM SYSIBM.SYSINDEXES WHERE TBNAME = 'your_table_name') ``` I have tested it, it is giving us all the columns which are used in indexes.
Get columns of index on DB2
[ "", "sql", "indexing", "db2", "" ]
Consider a database of accounts and deposits: ``` CREATE TABLE accounts ( id int not null primary key, name varchar(63) ); CREATE TABLE deposits ( id int not null primary key, account int references accounts(id), dollars decimal(15, 2), status enum('pending','complete') ); insert into accou...
try this ``` SELECT a.name, coalesce(SUM(d.dollars),0) as sums FROM accounts a left JOIN deposits d ON (a.id = d.account AND d.status='complete') group by a.name order by sums desc ``` you should use LEFT JOIN , and you should use GROUP BY also. [**LOOK DEMO**](http://sqlfiddle.com/#!2/91103/6)
You should use grouping by `a.name` (or maybe even `a.id`) and `LEFT OUTER JOIN` (if you want to get non-present values). EDIT: ``` SELECT a.name, SUM(d.dollars) FROM accounts a LEFT OUTER JOIN deposits d ON (a.id = d.account AND d.status='complete') GROUP BY a.name; ```
Get total of referenced tables' column
[ "", "mysql", "sql", "join", "sum", "" ]
I have a situation from which i have to get the data from three different tables and i want to use single query for that .How can we do this .Please help me . Here in the situation: ``` table_one emp_id dept_id name GT102 206 Test GT103 201 Test1 GT105 111 Test2 GT106 3...
Try this: ``` SELECT t1.name, t2.department, t3.salary FROM table_one t1 INNER JOIN table_two t2 ON t2.dept_id = t1.dept_id INNER JOIN table_three t3 ON t1.emp_id = t3.emp_id WHERE t1.name = 'Test2' ```
Try this: ``` Select table_two.department, table_three.Salary From table_one, table_two, table_three where table_one.emp_id = table_three.emp_id and table_one.dept_id = table_two.Dept_id and table_one.name='Test2' ```
How to get data from 3 diffrent tables in MySql
[ "", "mysql", "sql", "" ]
I'm only able to SELECT on a table. The table has a column called inty with a value of 0 or 1 I am currently selecting inty as: ``` SELECT inty AS InternetApproved FROM Table1 ``` Is there a way to reformat the data within the SQL SELECT so that if the value is 0 make it No and if the value is 1 make it Yes for dis...
Simple and easy way to achieve this is: ``` SELECT IF(inty = 1, 'YES', 'No') AS internetApproved FROM Table1 ```
``` SELECT CASE WHEN inty = 0 then 'No' WHEN inty = 1 then 'Yes' ELSE 'Maybe' END AS InternetApproved FROM Table1 ```
Change value from 1 To Yes In MySQL select statement
[ "", "mysql", "sql", "case", "" ]
I want to add a foreign key from Table `Customers`, `row= "Customer ID"` to Table Pet, `row= "Customer ID"`. ``` -- Table structure for table `Customers` CREATE TABLE IF NOT EXISTS `Customers` ( `CustomerID` varchar(50) NOT NULL, `Fname` varchar(50) DEFAULT NULL, `LName` varchar(20) DEFAULT NULL, `Tel` varcha...
Simple one. There is an row that contains the CustomerID that can't be matched. So first you need to remove/edit/handle the entry and than add a foreign key.
The `CustomerID` you're trying to enter in `PETS` table, does not exist in `CUSTOMERS` table, and that is why your Foreign Key constraint fails and throws error. You need to ensure that the CustomerIDs you're entering in your `Pets` table, exist in `Customers` table OR simply insert `NULL` in the `PETS.CUSTOMERID` fie...
Adding Foreign Key Error
[ "", "mysql", "sql", "database", "" ]
I have a table `student(name_std,age_std,address_std)`. When i write query ``` select * from Student ``` it displays ``` name_std age_std address_std Deepak 22 London Anjali 16 Srilanka ``` My requirement is that when I query `select * from Student`,It should give me output like ``` name_st...
Try `UNION` like below : ``` SELECT 'Name' as name_std,'Age' as age_std, 'Address' as address_std FROM dual UNION SELECT name_std,to_char(age_std),address_std FROM Student ```
I think you can just use `alias` to each column to achieve your desired output. ``` SELECT name_std as Name age_std as Age address_std as Address FROM Student ```
adding alias row in select query using union
[ "", "sql", "oracle", "" ]
Hello i would like to select, each auction id that is associated with a bid id with status ='won' and also each auction id which status is 'Expired' as two separated column in to my statement can someone help please, the first column will be call won and second one expired ``` SELECT Auction.AuctionID, D...
If the result you want is something like this: ``` AuctionID Month Won Expired ----------- ------------------------------ ---- ------- 1 January Won NULL 2 January Won NULL 3 January NULL Ex...
Can you try something like this, its not exact just an overview ``` *** SELECT Auction.AuctionID, DATENAME(mm, b1.Date) AS Month, COUNT(*) AS `Won`, (SELECT count(*) from BID b2 WHERE DATENAME(mm, b1.Date) = DATENAME(mm, b2.Date))-COUNT(*) AS `EXPIRED` FROM ...
Select 2 different value from 2 table
[ "", "sql", "sql-server", "" ]
My problem is this (using SQL Server 2008 R2). There is some date columns with types as `datetime`. So the original intention with the column was to store a date without any time. Then `datetime` was chosen as datatype. Sure it works but as the database is also logically connected to a UML-diagram I want to use the...
An easy way to do this is: ``` select p.* from Parcel p where DateOfArrival = cast(DateOfArrival as Date); ``` By casting the value to a date, the `datetime` portion is lost. If the original value equals this, then there is no time component.
A way to do this would be to convert it in your select statement, for example: ``` SELECT CONVERT(DATE, DateOfArrival) Date, *other columns* FROM Parcel P ``` Another solution, would be converting it to VARCHAR, formatting it in a yyyyMMdd format, like: ``` SELECT CONVERT(VARCHAR(8), DateOfArrival, 112) Date, *other...
Find rows in SQL that with date when it is stored as datetime?
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
My query: ``` SET @s_query = 'Select ROW_NUMBER() OVER (ORDER BY ' + @ColNames + ') AS ##RowNum, '+@ColNames+' INTO ##Results' + ' From TableA Where FirstName = ' +@Search+ ' ORDER BY FirstName'; ``` I am running the stored procedure with parameters: ``` @Search = 'Adam', @ColName = 'FirstName','LastName' ``` An...
Looks like you're just not quoting your string. The way your code comes out, to SQL it looks like: ``` Where FirstName = Adam ``` But you want it to look like: ``` Where FirstName = 'Adam' ``` So you'd want to change that line of your code to give it the single-quotes it needs. See the modified codeset below: ``` ...
The problem appears to be where you specify the criteria for `FirstName`, you have: ``` Where FirstName = ' +@Search+ ' ``` Which will literally be translated to: ``` Where FirstName = Adam ``` Note the missing quote around the search criteria `Adam`. Try this instead, to ensure the additional quotes are included:...
TSQL Where clause inside string query
[ "", "sql", "t-sql", "" ]
I have a query problem with count. I want to have a column with the number of persons registered to the course. So far, this is my query: ``` select courses.id, name, location, capacity, ( SELECT count(courses_requests.IDcourse) FROM courses_requests, courses WHERE courses_requests.IDcourse...
It may be simplier to aggregate the outer select, to eliminate the subquery, so something like: ``` SELECT c.id, c.name, c.location, c.capacity, COUNT(cr.IDcourse) AS RequestCount c.begin_date, c.end_date, c.price, ...
You should connect your subquery to main query: ``` select courses.id, courses.name, courses.location, courses.capacity, (SELECT count(courses_requests.IDcourse) FROM courses_requests, WHERE courses_requests.ID = courses.id and status != "rejected" ) as Regist...
SQL count problems
[ "", "mysql", "sql", "count", "" ]
CTE gives a below result ``` Name | StartDateTime | EndDateTime --------------------+-------------------------+------------------------ Hair Massage | 2014-02-15 09:00:00.000 | 2014-02-15 10:00:00.000 Hair Massage | 2014-02-15 10:00:00.000 | 2014-02-15 11:00:00.000 (X)Ha...
Okay Assuming this is your schema ``` CREATE TABLE dbo.StaffSchedule ( ID INT IDENTITY(1, 1) NOT NULL, Name Varchar(50), StartdateTime DATETIME2 NOT NULL, EndDateTime DATETIME2 NOT NULL ); CREATE TABLE dbo.BookedSchedules ( ID INT IDENTITY(1, 1) NOT NULL, StaffId INT...
ok try this, > create one more cte, ``` ,cte2 as ( select * from @Holidays union all select BookingID,StartdateTime,EndDateTime from @EventBooking ) ``` > then as usual ``` AND not exists (select 1 from cte2 h where cast(a.RepeatEventDate as date) between cast(h.startdatetime as date...
Ignore date list from CTE
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I need to add a `case` statement in a `where` clause. I want it to run either statement below depending on the value of TermDate. ``` Select * from myTable where id = 12345 AND TermDate CASE WHEN NULL THEN AND getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate) ELSE AND GETDATE < TermD...
Why not just use an `OR` condition? ``` SELECT * FROM myTable WHEN id = 12345 AND ((TermDate IS NULL AND getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate)) OR GETDATE() < TermDate) ```
Since we all posted three exact answers, obviously too much, here a version that uses your `case when` construction. use this: ``` select * from myTable where id = 12345 AND case when TermDate IS NULL AND getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate) then 1 when GETDATE < ...
Add Case Statement in Where Clause
[ "", "sql", "select", "switch-statement", "case", "" ]
I am trying to insert some records into a many to many table, the condition though is that a particular Id (uniqueidentifier) is in a comman seperated list of Id's (nvarchar). I had thought it was working but it only seems to compare it to the first Id in the list? How can I correctly use the list to insert the data ...
I use the following CSV to ROWS function: ``` CREATE FUNCTION dbo.CsvToRows ( @string NVARCHAR(MAX) ) RETURNS @ret TABLE ( [Index] INT NOT NULL PRIMARY KEY, Value NVARCHAR(500) ) AS BEGIN DECLARE @pos INT, @i INT = 0, @piece NVARCHAR(500) IF RIGHT(RTRIM(@string),1) <> ',' ...
I would put the comma delimited GUID list into a table and then use that in your `IN` Operator: ``` -- get comma delimited list of GUIDs declare @GUIDs nvarchar(369) -- 10 GUIDs and 9 commas set @GUIDs = cast(newid() as varchar(36)) while len(@GUIDs) < 369 begin set @GUIDs = @GUIDs + ',' + cast(newid() as ...
How can I check a uniqueidentifier is in a comma delimited list of ids?
[ "", "sql", "sql-server", "t-sql", "" ]
This is my sql query: ``` CREATE TABLE items( id int(3) , name VARCHAR(255) , amount INT(4), PRIMARY KEY (`id`) ); -- BRONIE DO WALKI WRĘCZ INSERT INTO items (id, name, amount) VALUES ('1', 'KATANA','0'); INSERT INTO items (id, name, amount) VALUES ('2', 'HATCHET','0'); INSERT INTO items (id, name, amount) VALUES (...
to write the comment `--` must be followed by a white space. see more in the [MySQL manual - 9.6 Comment Syntax](https://dev.mysql.com/doc/refman/5.1/en/comments.html) BTW, you have the same problem in other lines: * `--HANDGUN AMMO` change to `-- HANDGUN AMMO` * `--SHOTGUN AMMO` change to `-- SHOTGUN AMMO` * `--ASS...
The [MySQL documentation](https://dev.mysql.com/doc/refman/5.1/en/comments.html) specifies a space between the dashes and the comment: ``` -- HANDGUN ``` Note that 'Shotgun', 'SMG', etc will also fail, so you'll have to adjust those comments as well.
sql newbie gets sql error, dont know why
[ "", "mysql", "sql", "syntax", "" ]
I have a factory table with factoryname: `select factoryname from factory` I then have a products table: `select productcode from products` I want to create a list that has products for all factory. so output : ``` mill 1 product 1 mill 1 product 2 mill 1 product 3 mill 2 product 1 mill 2 product 2 mill 2 product 3...
If you want to list all the factory names and all products, you can use a cross join like this: ``` select factoryname, productname from factory cross join products ``` A `Cross Join` is basically a Cartesian product of 2 tables, resulting in (m \* n) records if table 1 has m and table 2 has n records.
SQL is a set based language, so you should try not to use loops in SQL whereever possible. It will hurt performance. What you want to do, is use a JOIN to JOIN 2 tables together: ``` SELECT factory.factoryname, products.productcode FROM factory, products INNER JOIN products.factory_id = factory.factory_id ``` Someth...
MSSQL - Loop through table and use field value in new query
[ "", "sql", "loops", "" ]
I am using the following stored procedure to get the newest date out of a column which works fine. Can someone tell me how I have to amend this that I also get the rest of the data of this record selected (i.e. the one with the max date) ? The column in question is called "updated" and is formatted as datetime so the ...
You could take the analytic approach: ``` SELECT * FROM (SELECT col1, col2, col3, col4, RANK() OVER (PARTITION BY col1, col2, col3 ORDER BY updated DESC) AS rk FROM MeetingDetails WHERE itemstatus = 'active') t WHERE rk = 1 ```
``` SELECT col1, col2, col3, col4, updated FROM MeetingDetails WHERE updated in ( SELECT MAX(updated) FROM MeetingDetails WHERE itemStatus = 'active' ) ``` This should be what you're looking for. From here, if you need to narrow it down further, just add more criteria to your where cl...
SQL Server: Get data from record with max date / newest date
[ "", "sql", "sql-server", "datetime", "select", "max", "" ]
This is my sqldatasource ``` <asp:SqlDataSource runat="server" ID="get_client_users" ConnectionString="<%$ ConnectionStrings:local %>" SelectCommand="SELECT * FROM users WHERE clientid = @clientid" CancelSelectOnNullParameter="False"> <SelectParameters> <asp:Parameter Name="clientid" Type="Int32" Conv...
**UPDATE:** ``` SELECT * FROM users WHERE ISNULL(clientID, -1) = ISNULL(@ClientID, -1) ``` This is assuming that clientID will never be -1 in the database.
Since you have complete control over the `SELECT` command, I'd have thought: ``` SELECT * FROM users WHERE clientid = @clientid OR (@clientid is null and clientid is null) ``` Would work for you.
Pass is NULL instead of = Null
[ "", "asp.net", "sql", "sql-server", "visual-studio-2012", "sqldatasource", "" ]
I have a table with over a billion records. In order to improve performance, I partitioned it to 30 partitions. The most frequent queries have `(id = ...)` in their where clause, so I decided to partition the table on the `id` column. Basically, the partitions were created in this way: ``` CREATE TABLE foo_0 (CHECK (...
For non-trivial expressions you have to repeat the more or less verbatim condition in queries to make the Postgres query planner understand it can rely on the `CHECK` constraint. Even if it seems redundant! [Per documentation](http://www.postgresql.org/docs/current/static/ddl-partitioning.html): > With constraint exc...
Unfortunately, partioning in postgresql is fairly primitive. It only works for range and list based constraints. Your partition constraints are too complex for the query planner to use to decide to exclude some partitions. In the [manual](http://www.postgresql.org/docs/current/static/ddl-partitioning.html) it says: >...
Partitioned table query still scanning all partitions
[ "", "sql", "database", "postgresql", "partitioning", "" ]
### What I am doing I have a query in Access which as SQL view of: ``` SELECT Projects.*, Projects.MySortField FROM Projects ORDER BY Projects.MySortField DESC; ``` This query works fine and sorts my data correctly. It is also very, very clean to look at and to understand what is happening. However, when I load it ...
The problem you are running into is that by having Projects.\* as well as a named field, you are ending up with two output fields of the same name. I'm not sure why you feel you must use "\*" instead of just explicitly naming the fields (which is generally considered the best practice) which would allow you to sort wit...
This ``` SELECT Projects.* FROM Projects ORDER BY Projects.MySortField DESC; ``` can be done. But if you insist on adding **, Projects.MySortField**,then ``` SELECT Projects.*, Projects.MySortField as whatever FROM Projects ORDER BY Projects.MySortField DESC; ```
Access query using * and sort criteria on columns - how to make field show just column name?
[ "", "sql", "sql-server", "vba", "ms-access", "" ]
I'm running on a 2012 MS-SQL server and have a table USER with Age, Gender among other fields and a SALES table with sales records. I'm currently calculating the Sales Leaderboard showing an list of Sales People ordered by their TOP Sales so to give an example this list returns various sales rep based on their Top Sal...
The first CTE gets the max sales for each person. The second uses the windowing functions `rank()` and `count()` with an appropriate `over()` clause to calculate the position and totals. ``` with C1 as ( select U.UserId, U.Gender, U.Age, max(S.TotalSale) as TotalSale from dbo.[User] as U...
[jsFiddle](http://sqlfiddle.com/#!6/d41d8/14970) -- edit: it's a sqlFiddle, not jsFiddle :) ``` DECLARE @UserId INT = 4 ;with overall as ( SELECT u.Name, u.UserId, RANK() OVER (ORDER BY max(s.TotalSale) DESC) OverallRank FROM User u JOIN Sales s on u.UserId = s.UserId group by u.Name, u.UserId ), age as ( S...
TSQL calculating various % based on different fields
[ "", "sql", "sql-server", "t-sql", "" ]
I have a basic stored procedure that adds a new record to a table with a structure like the following. The table also has a column "itemID" that is set to auto-incrementing to create a unique id for each record. I would like to use Output to get this id from the new record I inserted and then use this to add a new rec...
``` BEGIN SET NOCOUNT ON; /* Here declare a Table Variable */ DECLARE @Table_Var TABLE(itemID INT) INSERT INTO Table1(colA,colB,colC) OUTPUT inserted.itemID INTO @Table_Var(itemID) SELECT @colA,@colB,@colC /* Now do the insert into Table 2*/ INSERT INTO TABLE2 ...
Try with `SCOPE_IDENTITY()`: ``` ALTER PROCEDURE [dbo].[CreateStuff] @colA datetime, @colB varchar(50), @colC nvarchar(20), @Valueout int output AS BEGIN SET NOCOUNT ON; INSERT INTO Table1 ( colA, colB, colC ) SELECT @colA, @colB,...
SQL Server: Use output from first insert to insert into second table
[ "", "sql", "sql-server", "t-sql", "output", "sql-insert", "" ]
I have an `Insert` stored procedure which will feed data to `Table1` and get the `Column1` value from `Table1` and call the second stored procedure which will feed the Table2. But when I call The second stored procedure as: ``` Exec USPStoredProcName ``` I get the following error: > Transaction count after EXECUTE ...
If you have a TRY/CATCH block then the likely cause is that you are catching a transaction abort exception and continue. In the CATCH block you must always check the [`XACT_STATE()`](http://technet.microsoft.com/en-us/library/ms189797.aspx) and handle appropriate aborted and uncommitable (doomed) transactions. If your ...
I had this problem too. For me, the reason was that I was doing ``` return commit ``` instead of ``` commit return ``` in one stored procedure.
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0
[ "", "sql", "sql-server-2012", "sqlexception", "" ]
I have two tables `BankMaster` and `#tmp_BankMaster`. The `#tmp_BankMaster` table is inherited from `BankMaster` table. So, data structures are same. Even some data also exist in `#tmp_BankMaster` table is the same as `BankMaster`. Now I want to insert all non-existing data from `#tmp_BankMaster` into `BankMaster`. I h...
No, you can't use NOT IN, but you can use NOT EXISTS,You are using composite key you need to make sure those records should be selected from #tmp\_BankMaster for which your composite key (BankID and CompanyID doesn't exist in BankMaster). Try this ``` insert into BankMaster Select * From #tmp_BankMaster tmp wh...
You need to check the values you are trying to insert into BankMaster. It appears as if you are trying to insert a combination of CompanyID and BankID that already exists in the table.
What's going wrong with this sql query?
[ "", "sql", "sql-server", "" ]
I have been at this for the past two hours and have tried many different ways in regards to subquery and joins. Here's the exact question "Get the name and city of customers who live in the city where the least number of products are made" Here is a snapshot of the database tables ![](https://i.stack.imgur.com/MNaIW....
I have just figured out my own answer. I guess taking a break and coming back to it was all I needed. For future readers this answer will use a subquery to help you get the min of a column and compare a different column (of that same row) to a different tables column. This example is getting the city where the least n...
In Postgresql you have sophisticated tools, viz., windowing and CTEs. ``` WITH find_least_sumq AS (SELECT city, RANK() OVER ( PARTITION BY city ORDER BY SUM(quantity) ) AS r FROM products) SELECT name, city FROM customers NATURAL JOIN find_least_sumq /* ON city */ WHERE r=1; /* rank 1 is smallest summed qua...
PostgreSQL: get the min of a column with it's associated city
[ "", "sql", "postgresql", "" ]
I want a full backup of my SQL Server database using a scheduled batch file. I tried many codes from this website but nothing worked. I just want to know which exe file actually creates the backup so I can directly execute that file from cmd. The codes which I tried are ``` echo -- BACKUP DATABASE -- set /p DATABASENA...
Here's the code for above solution ``` echo off cls echo -- BACKUP DATABASE -- ::set db name set DATABASENAME=db_name :: set path and format set BACKUPFILENAME=PATH\%DATABASENAME%.bak :: set server name set SERVERNAME=server_name echo. ::backup execution sqlcmd -S %SERVERNAME% -d COFI -U vutagi -P vu1234 -Q "BACKUP DA...
> I just want to know which exe file actually creates the backup so I can directly execute that file from cmd. You have zero understanding how sql server works, right? The file that runs the backup is the server executable that you can not execute fom the command line - it is basically the exe that already runs to ru...
Which file is executed in SQL Server 2005 while backing up data
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I am a beginner in SQL and I need help to get the solution for this condition. I want Output as a name of any person who managed to ride the Super Rollercoaster more than 50 times on a single day. ``` create table visitor( visitID char(n), name char(n) not null, primary key (visitID) );...
WHERE should be put before GROUP BY ``` SELECT distinct Name FROM attractionVisit Natural Join ticket Natural Join visitor Natural Join attraction WHERE attractionName = 'Super Rollercoaster' group by VisitID, day having count(*) > 50; ```
``` SELECT distinct(v.Name) FROM attractionVisit av inner Join attraction a on av.attractionID=attractionID inner join ticket t on av.ticketID=t.ticketID inner join visitor v on t.visitID=v.visitID WHERE attractionName = ‘Super Rollercoaster’ group by v.na...
SQL statement to output record of person that has more than x counts of a condition
[ "", "sql", "" ]
how to join userid to user and get the username ? I really appreciate any help.Thanks in Advance. <http://sqlfiddle.com/#!2/ac600/1> ``` CREATE TABLE if not exists tblA ( id int(11) NOT NULL auto_increment , user varchar(255), category int(255), PRIMARY KEY (id) ); CREATE TABLE if not exists tblB ( id int(11) N...
Use `JOIN`, for example: ``` SELECT tblB.username, groups.*, @rank:=@rank+1 AS rank FROM (select user, category, count(*) as num from tblA where category=1 group by user, category order by num desc, user) AS groups -- left join: in case if data integrity fai...
You just need to do left join ``` SELECT groups.*, @rank:=@rank+1 AS rank FROM (select user, category, count(*) as num, tblB.username from tblA left join tblB on tblA.id = tblB.userid where category=1 group by user, category order by num desc, user) AS groups CROSS JOIN (SELECT @rank:=0) AS init ``` See...
join user id from tblB to user from tblA and get username
[ "", "mysql", "sql", "" ]
Using this we can create procedure then how to delete,alter...etc,Can any one help me how to delete procedure. ``` USE [PSI Data] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER Procedure[dbo].[savepsi] @Psiid int, @Name varchar(50), @DOB int, @Sex varchar(50), @Mobile int, @Cusaddress varchar(50), @P...
Try this USE [PSI Data] DROP PROCEDURE [dbo].[savepsi]; GO
To remove a stored procedure you can use the command [`DROP PROCEDURE`](http://technet.microsoft.com/en-us/library/ms174969.aspx) ``` DROP PROCEDURE [dbo].[savepsi] ```
How to delete a stored procedure?
[ "", "mysql", "sql", "sql-server", "stored-procedures", "" ]
My Query looks like ``` $search_query = db_query("SELECT nd.nid, users.name, nd.type FROM node as nd LEFT JOIN node_revisions as nd_rev ON nd_rev.nid = nd.nid AND nd_rev.vid = nd.vid LEFT JOIN users ON nd.uid = users.uid WHERE nd.status = 1 AND nd_rev.body LIKE LOWER('%node/100%') AND nd.nid NOT IN(SELECT DISTINCT...
Oh ya... I got an resolution for this.. I redefined my query like below and it gives me result as expected.. ``` $search_query = db_query("SELECT nd.nid, users.name, nd.type FROM node as nd LEFT JOIN node_revisions as nd_rev ON nd_rev.nid = nd.nid AND nd_rev.vid = nd.vid LEFT JOIN users ON nd.uid = users.uid WHERE ...
Try removing the `%` after 100 so the search won't consider any digit after 100, like this: ``` LOWER('%node/100') ```
How to search exact string using MySql Query which avoids extended values?
[ "", "mysql", "sql", "" ]
I'm trying to convert a date format stored m/d/yyyy to a 'yyyymmdd' character format, without the need to cast the date column every time I want to use the column in my query. Currently I'm casting and formatting dates as chars: `((cast(cast(invitation_date as CHAR(8)) as date format 'YYYYMMDD'))`. Is there a way to ...
If source is a DECIMAL yyyymmdd you can do ``` CAST(invitation_date - 19000000 AS DATE) AS newcol ``` Teradata allows an alias to be used in any place, so you can simply do ``` WHERE newcol > DATE ``` Of course best case would be to change those columns to DATE during load.
Navigate to File->Options -> Results Format -> Teradata. Then select the datatype Date and enter yyyyMMdd. Your result set will now return the specified date format. Let me know if this will solve your issue. ![enter image description here](https://i.stack.imgur.com/F9NEo.png) ![enter image description here](https://...
Converting date to character format in SQL
[ "", "sql", "teradata", "" ]
I'm working in sql server 2012 where I have table `Students` which contain `fields: StudentId, Name, City, Username, Password`. I need split table Students into next tables: `Students` and `Users`. And table `Users` must be have next fields: `UserId, Username, Password`. And table `Students` must be have: `StudentId...
You can do it in the following steps: Create Users table. Since you don't have UserID, you can generate it using an identity column. ``` CREATE TABLE Users ( UserID bigint IDENTITY(1,1) PRIMARY KEY NOT NULL, Username nvarchar(255), Password nvarchar(255) ) ``` Insert data into Users table ``` INSERT INTO Users ( Us...
Populate Students Table 1st , since you already have Students table in your table database you cannot have another table called students, so call it students\_new inititally. **Add UserID Identity COlumn to yout Original Table** ``` ALTER TABLE Students ADD UserID INT IDENTITY(1,1) ``` **Students Table** ``` SELECT...
How to split one table into two
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I am loading data from Excels into database on SQL Server 2008. There is one column which is in `nvarchar` data type. This field contains the data as ``` Text text text text text text text text text text. (ABC-2010-4091, ABC-2011-0586, ABC-2011-0587, ABC-2011-0604) Text text text text text text text tex...
I have worked this problem out with the following guides: [Split Multi Value Column into Multiple Records](http://microsoft-ssis.blogspot.se/2012/11/split-multi-value-column-into-multiple.html) & [Remove Multiple Spaces with Only One Space](http://social.msdn.microsoft.com/Forums/sqlserver/en-US/34ce1b87-fee7-4...
If I understand correctly, "ABS-####-####" will be the value coming through in the column and the numeric part is variable in length. If that is the case, maybe this will work. Use a "Derived Column" transformation. Lets say we call "ABC-####-####" = Column1 ``` SUBSTRING("Column1",(FINDSTRING("Column1","-",2)+1),LE...
SQL Parse NVARCHAR Field
[ "", "sql", "sql-server", "parsing", "ssis", "" ]
Hi Can anyone help with the problem below, I have a stored procedure which depending on the month and date, depends on which image is returned. I have found plenty of examples of how to solve this when the data is in a table, but no solutions on how I'm doing it. The reason why I'm doing it this way is because it will...
You don't need the inner `SELECT`s: ``` SELECT --Set image for xmas CASE WHEN @CurrentMonth = 12 AND @CurrentDate = 25 THEN 'imagetest.png' --Set for easter WHEN @CurrentMonth = 3 AND @CurrentDate = 19 THEN 'imagetest2.png' --Keep setting images for events WHEN @C...
The `AS URL` needs to be at the end of your case statement ``` CASE ... END AS URL ```
Return Column name in case statement but no table involved
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a large database of URLs, and I have duplicates from trailing slashes. I would like find duplicate values of those ending with a trailing slash, but not urls with text after the trailing slash, such as `http://www.google.com/asdfasdf` ``` CREATE TABLE link_info ( id INT, url VARCHAR(32) ); INSERT INTO link...
Your query will return every url trimmed. I think you need something like this: ``` SELECT TRIM(TRAILING '/' FROM url) trimmed_url FROM link_info GROUP BY trimmed_url HAVING COUNT(DISTINCT url)>1 ``` Please see fiddle [here](http://sqlfiddle.com/#!2/81038/25). **Edit** If there are no exact duplicates, and you just...
you may use this ``` SELECT TRIM(TRAILING '/' FROM url) url FROM link_info group by SUBSTRING_INDEX(url, '.com', 1) ``` But this works only whith links which have `.com` so with `.net` or `.something` you add a union [**DEMO HERE**](http://sqlfiddle.com/#!2/81038/22)
select near duplicates with trailing slashes
[ "", "mysql", "sql", "trim", "" ]
Everytime I try to create a new Database in SQL—haven't accomplished to create any, so far. Please, help me with a detailed solution for this. ## TITLE: Microsoft SQL Server Management Studio Cannot write property IsFileStream.This property is not available on SQL Server 7.0. (Microsoft.SqlServer.Smo) For help, clic...
This is due to you using older MS SQL Management studio. Download the new version in this link: <https://learn.microsoft.com/es-es/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver15> I faced the same issue with having SQL 2008R2 and when I installed 2019, I had the same error as you on manageme...
SQL Server Management is unable to set up the default property while creating a database using previous version of SQL Server Management Studio.
Cannot write property IsFileStream
[ "", "sql", "sql-server", "ssms", "" ]
I have no idea how to finish this query.... The question asks: > "For each person who acted in a movie in 2010, find their name > and total pay in all movies in which they have acted (i.e. including > those not in 2010)." The table required: (where title = Movie title, and year = Movie year, and Pay = actors pay) `...
You can do this with a single aggregation and `having` clause: ``` select ai.name, sum(ai.pay) from actedin ai group by ai.name having sum(case when ai.year = 2010 then 1 else 0 end) > 0; ``` The `having` clause counts the number of movies that each "name" acted in in 2010. If this number is greater than 0, then the ...
You can also use exists with a subquery. ``` select name, sum(pay) from actedin a where exists (select 1 from actedin b where a.name = b.name and year = 2010) group by name ```
SQL query help select from multiple tables
[ "", "mysql", "sql", "" ]
Let's say i've got this database: ``` book | idBook | name | |--------|----------| | 1 |Book#1 | category | idCateg| category | |--------|----------| | 1 |Adventures| | 2 |Science F.| book_categ | id | idBook | idCateg | DATA | |--------|--------|----------|--------| | 1 | 1 |...
Solution using EXISTS: ``` select * from book b where exists (select 'x' from book_categ x where x.idbook = b.idbook and x.idcateg = 1) and exists (select 'x' from book_categ x where x.idbook = b.idbook and x.idcateg = 2) ``` Solution using join with a...
You could try using `ALL` instead of `IN` (if you only want values that match all criteria to be returned): ``` SELECT book.* FROM book, book_categ WHERE book_categ.idCateg = ALL(1 , 2) ```
Select from one table but filtering other two
[ "", "mysql", "sql", "" ]
**QUERY #1** ``` SELECT dbo.CLIENT.CLIENT_ID, dbo.CLIENT.GOC, dbo.SALES_UW_REGION.SALES_UNDERWRITING FROM dbo.CLIENT LEFT OUTER JOIN dbo.SALES_UW_REGION ON dbo.CLIENT.GOC = dbo.SALES_UW_REGION.GOC WHERE (dbo.CLIENT.CLIENT_ID = 23721) CLIENT_ID, GOC, SALES_UNDERWRITING 23721...
I think your confusion involves a misunderstanding of the first result set: ``` CLIENT_ID, GOC, SALES_UNDERWRITING 23721 332 Underwriting 23721 332 Sales ``` Though there are two rows in this result set, the results represent data from only one row in the Client table. The join condition allowed the single row fr...
You have one row in your `CLIENT` table for `CLIENT_ID = 23721`. You're left joining the other table which has multiple rows for `CLIENT_ID = 23721` (when joined with criteria in your first query), but when the joining criteria is altered it excludes one of those rows from the `RIGHT` table. You're getting all record...
LEFT OUTER JOINs not acting as expected
[ "", "sql", "sql-server", "" ]
Below are the tables in MySQL ``` Table:ShopInfo ShopCode ShopName -------- ------- X Xylophon Y Yellow Z Zoota K Kite Table: Income Shop Date Earnings ----- ---------- -------- X 2014-10-17 4000 Y NULL NULL Y ...
Try putting the having clauses under where clauses : ``` SELECT ShopInfo.ShopName, IFNULL( SUM(Income.Earnings), 0 ) AS NovEarn FROM Income JOIN ShopInfo ON Income.Shop=ShopName.ShopCode WHERE (MONTH(Income.Date)=11 AND YEAR(Income.Date)=2014) OR Date IS NULL GROUP BY Income.Shop ORDER BY NovEarn DESC ```
Filtering income by month has to be done BEFORE you group by show code. Use a where statement for that part. But then you will have the problem of keeping shops with no income. So you should select first from ShopInfo, and then left join on income, so that if there are no acceptable income, the shop will still be displ...
Filtering data after GROUP BY() or vice versa?
[ "", "mysql", "sql", "database", "" ]
I'm trying to create the following pseudocode in MySQL. I have the following tables: * specials * product\_filter The `product_filter` table only has two columns, `product_id` and `filter_id` I'd like to come up with a SQL that: 1. Reads all product\_ids from the `specials` table and puts them in the `product_filte...
Try this, using a `CASE` to determine what the `filter_id` is (this will set anything that doesn't have a price in those boundaries equal to 0): ``` INSERT INTO product_filter (product_id,filter_id) SELECT product_id, (CASE WHEN price < 100 then 1 WHEN price >= 100 AND price < 500 then 2 WHEN price >= 500 ...
try this query (you didn't specify for values higher than 1000 so it'll make filter\_id 4 if values are greater than 1000). ``` INSERT INTO product_filter (product_id,filter_id) SELECT product_id, CASE WHEN price < 100 THEN 1 WHEN price BETWEEN 100 AND 500 THEN 2 WHEN price BETWEEN 500 A...
Insert into table values from another table only if they meet certain criteria
[ "", "mysql", "sql", "opencart", "" ]
i have the following tables: ``` **entries** entry_id | date | engineer | project **entries_allowanes_map** entry_id | allowance_id **allowances** allowance_id | allowance_name ``` I want to create a SELECT query that will give the following result: ``` entry_id | date | engineer | project | allowance_name1 | allo...
I would propose doing this with `group_concat()`. It doesn't put the values in separate columns, but it does put everything for a given entry on one row: ``` select e.entry_id, e.date, e.engineer, e.project, group_concat(a.allowance_name) as allowances from entries e join entries_allowances_map f on ...
Here is the query that I got: It outputs your expected results in different columns: ``` SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( '(SELECT max(CASE WHEN AL.ALLOWANCE_ID = ''', ALLOWANCE_ID, ''' THEN 1 END) AS `', ALLOWANCE_ID, '` FROM entries_allowanes_map AL WHERE E.ENTRY_I...
MySQL - Select Query with junction table to one row
[ "", "mysql", "sql", "select", "join", "" ]
This is table structure ``` id 1 2 3 4 5 6 ``` I need result like this ``` id even odd 1 0 1 2 1 0 3 0 1 4 1 0 5 0 1 6 1 0 ``` I tried ``` select id %2=0 then 1 else 0 end or id%2 <>0 then 1 else 0 odd from table ```
How about ``` select id, ~id & 1, id & 1 from t ```
Take a look at the [`CASE`](http://technet.microsoft.com/en-us/library/ms181765.aspx) keyword. It works very similarly to what you're trying to do in your `SELECT` statement. In addition, if you want to select multiple columns, separate them with a comma. The [`OR`](http://technet.microsoft.com/en-us/library/ms188361.a...
Even or odd in SQL
[ "", "sql", "sql-server", "t-sql", "select", "" ]
So im trying to add fields to a database. It is .mdb database, microsoft access. The Name of the table is Contacts. ``` Dim con As New OleDb.OleDbConnection Dim dbProvider As String Dim dbSource As String Dim ds As New DataSet Dim da As OleDb.OleDbDataAdapter Dim sql As String dbProvider = "P...
As other answers have already explained you need to use square brackets around column names that contain spaces, but also you need to add a value for the fields otherwise you cannot execute the command. I will try to show a complete example ``` Dim dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" Dim dbSource = "Dat...
Put column names with spaces between squares brackets [] For example `[Address Line 1]` Cheers
Inserting MS Access Row Into Database using vb.net
[ "", "sql", "database", "vb.net", "oledbcommand", "" ]
I am looking for a query which fetches me the data that is different compared to the previous row, A sample code (with table creation and data) ``` create table #temp (id int, eid int, name char(10),estid int, ecid int, epid int, etc char(5) ) insert into #temp values (1,1,'a',1,1,1,'a') insert into #temp values (...
You can do this with a simple self-join and appropriate comparison: ``` select t.* from #temp t left outer join #temp tprev on t.id = tprev.id + 1 where tprev.id is null or t.name <> tprev.name or t.estid <> tprev.estid or t.ecid <> tprev.ecid or t.epid <> tprev.epid or t.etc <>...
For SQL Server 2012 ([SQL Fiddle](http://sqlfiddle.com/#!6/0c09c/1)) ``` WITH CTE AS (SELECT *, LAG(eid) OVER (ORDER BY id) AS prev_eid, LAG(name) OVER (ORDER BY id) AS prev_name, LAG(estid) OVER (ORDER BY id) AS prev_estid, LAG(ecid) OVER (ORDER ...
Deleting records that are similar with previous one SQL Server
[ "", "sql", "sql-server", "" ]
I've tried searching for this and I'm not quite sure how to phrase exactly what I'm after, but I'll show what I've got and what I want. Also my first question here so I apologise if I get anything wrong! Firstly, I have this link-table with foreign keys: ``` |ID|Value| +--+-----+ |1 | 70| |1 | 130| |2 | 60| ``` ...
``` Select * From table where id Not In (Select distinct id From table Where value = 70) ``` or ``` Select * From table t where Not exists (Select * From table where id = t.id and value = 70) ```
You can use a subquery and [`NOT IN`](http://www.w3resource.com/mysql/comparision-functions-and-operators/not-in.php) condition ``` SELECT tb.* FROM table tb WHERE tb.ID NOT IN ( SELECT a.ID FROM table a where a.Value = 70 ) ```
Exclude rows based on column value when second column value is found
[ "", "mysql", "sql", "" ]
I am looking to simplify this confusing left outer join statement into something easier to read by possibly using a where-statement ``` Select approved.orderId From (select distinct orderId from OrderLine where isApproved = 1 and isDismissed = 0) approved left outer join (select distinct orderId from Ord...
This should do: ``` SELECT DISTINCT O.orderId FROM OrderLine O WHERE O.isDismissed = 0 AND O.isApproved = 1 AND NOT EXISTS( SELECT 1 FROM OrderLine WHERE isApproved = 0 AND isDismissed = 0 AND orderId = O.OrderId) ```
`except` should work pretty fast for your usecase, and remove the need for both joins and inner queries: ``` SELECT DISTINCT orderId FROM orderline WHERE isApproved = 1 and isDismissed = 0 EXCEPT SELECT orderId FROM orderline WHERE isApproved = 0 and isDismissed = 0 ```
Convert left outer join to where statement
[ "", "sql", "sql-server", "" ]
I'm trying to make a SQL query that will search for user id and populate the query with the username. These are my tables: * Table Names: 'users' and 'schedule' ![enter image description here](https://i.stack.imgur.com/Zt1T5.png) This is how I want it to look like, where 'schedule' table now shows the username inst...
This is the query you are looking for: ``` SELECT s.REFID, s.jobnum, s.customer, u1.username AS engineer, u2.username AS sales FROM schedule s, users u1, users u2 WHERE s.engineer=u1.id AND s.sales=u2.id ``` You need to reference the `users` table two separate times, since you are checking in one sub-query for ...
Following Query will give you the expected result: ``` SELECT s.refid as refid, s.jobnum as jobnum, s.customer as customer, u_engg.username as engineer, u_sales.username as sales FROM user u_engg join schedule s on u.id = s.engineer join user u_sale on u_sale.id = s.sales ```
MySQL Query phpmyadmin
[ "", "mysql", "sql", "" ]
I have a script inserting a formula into a field in my database. The script looks like this: ``` insert into Export..DataDictionary values(100001, 'Modifier 3', 'Modifier 3', 476, 'IsNull(Modifier_3, '''')', 'Char', NULL, NULL, 'Y', NULL, NULL, NULL, NULL ,'N', NULL, 'Y', 'Modifier_3') ...
When I run into situations with quotes inside strings I use QUOTENAME. In your case I would do like this ``` DECLARE @item As varchar(100) = 'IsNull(Modifier_3, {0})'; SET @item = REPLACE(@item, '{0}', QUOTENAME('', '''')); INSERT INTO Export..DataDictionary VALUES (..., @item, ...) ``` You can of course make it a ...
If you want to have two apostrophe the right way, I believe, is to put six apostrophe in your query.I really don't know how it works in your own server. ``` insert into Export..DataDictionary values(100001, 'Modifier 3', 'Modifier 3', 476, 'IsNull(Modifier_3, '''''')', 'Char', NULL, NULL, 'Y', NULL, ...
SQL inserting one less apostrophe in to client than on my test server
[ "", "sql", "string", "t-sql", "insert", "apostrophe", "" ]
I have a postgres table that looks something like this: ``` proposal_id | nih_budget_start | nih_budget_end | nsf_start_date | nsf_end_date | award_amount proposal_A | 03/01/2000 | 12/31/2000 | | | 10,000 proposal_B | | | 08/01/2005 | 0...
Option 1: use [`COALESCE`](http://www.postgresql.org/docs/current/interactive/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL) ``` SELECT proposal_id, start_year, end_year , award_amount/((end_year - start_year) + 1.0) AS avg_award FROM ( SELECT proposal_id , extract(year FROM COALESCE(nih_bu...
From your clarification it seems it would be better for you to get a list like below: ``` proposal_ID | years_funded | average_award proposal_A | 2000 | 10,000 proposal_B | 2005 | 1,000,000 proposal_B | 2006 | 1,000,000 proposal_B | 2007 | 1,000,000 proposal_B | 2008 ...
Enumerate years between two dates with calculated values
[ "", "sql", "database", "postgresql", "view", "generate-series", "" ]
1) The below query is run over 1 Million records minimum. Right now it is giving results in `70ms to 1s`. Is the performance good. What is the ideal time in which the query should return results. (MySql InnoDB system) all columns are in same table ``` SELECT * FROM rgb WHERE ((tcount = 16 AND r1 = 3 AND r...
I would try to have a covering index for your query of ( r1, r2, r3, tcount ) and have the WHERE clause something like ``` where r1 in ( 3, 5, 8 ) AND r2 in ( 3, 5, 8 ) AND r1 != r2 OR ( r1 = 3 and r2 = 5 and r3 = 8 and tcount = 16 ) ```
why not use this simpler one ? instead of using a bunch of `OR`s ``` SELECT * FROM rgb WHERE ((tcount = 16 AND r1 = 3 AND r2 = 5 AND r3 = 8) OR (r1, r2) IN ((8,5),(5, 8), (3, 8),(5,3),(3,5),(8,3)) order by case when (tcount = 16 AND r1 = 3 AND r2 = 5 AND r3 = 8) then 1 else 2 end ```
SQL query optimization for 1million record
[ "", "mysql", "sql", "" ]
I am getting TF400997 when I am trying to configure TFS Scheduled backup using TFS Admin console. Here is my setup: SQL Server name: Machine1 SQL Server service running under: sqlserverservice@domain.com (which is a domain user and local admin on Machine1 and Machine2) SQL Server agent service running under: sqlserver...
Backup is executed by TFS Job Service: check also TFS user's permissions.
Please try this one: * configure your SQL Account to run under `domain\tfsservice` instead of `tfsservice@domain.com` * configure your TFSBackup
TF400997: Configuring Scheduled backup with TFS 2013
[ "", "sql", "tfs", "backup", "" ]
I have problem in creation a field name `staus` which `type-BOOLEAN`. and length is 1. When I press the go button then this Massage Arrived ``` SQL query: ALTER TABLE `abcd` ADD `status` BOOLEAN( 1 ) BINARY NOT NULL DEFAULT NULL MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manua...
``` ALTER TABLE `abcd` ADD COLUMN `status` BIT NOT NULL DEFAULT 0 ``` 1. If you want to create only a single bit field use `BIT`. You had 2 data types in your statement. 2. Your default value was `null` but you don't want to allow that: `NOT NULL`. Use `0` as default value instead.
The correct syntax for [`ALTER TABLE`](http://dev.mysql.com/doc/refman/5.1/en/alter-table.html) requires `COLUMN` after `ADD` ``` ALTER TABLE `abcd` ADD COLUMN ... ```
Error in creatinng a field in the table
[ "", "mysql", "sql", "" ]
Table Structure ``` Name qty Milk 12 Bread 10 Pen 100 Pencl 100 ``` My sql code to get the maximum qty ``` SELECT Name, MAX(qty) FROM item ``` But it is giving Milk 100 as the answer. how to get the correct answer?
I think you are looking for this: ``` SELECT Name FROM item WHERE qty = (SELECT MAX(qty) FROM item) ```
``` SELECT Name,qty FROM item ORDER BY qty DESC LIMIT 1 ``` **[Fiddle](http://sqlfiddle.com/#!2/3c66e/1)**
getting mysql max() value
[ "", "mysql", "sql", "" ]
I Have 2 tables ``` Users -------------------------------------------- Uid | Name | -------------------------------------------- 1 | sdfa | 2 | dsf | ``` And Second Table as ``` Log -------------------------------------------- Uid | log | size | file | ...
There's no distinct `rank` function in MYSQL. But you could utilize a variable in that matter. Check on [SQLFIDDLE HERE](http://sqlfiddle.com/#!2/50105/1) for the sample. The time stamp is not formatted, which you may do on your own. Table users ``` UID NAME 1 a 2 b ``` Table logs ``` UID LOG SIZE ...
This will give you the latest log entry for each user. If your tables are properly indexed, it should be fast. ``` SELECT a.* FROM log a INNER JOIN ( SELECT uid, MAX(timestamp) max_date FROM log GROUP BY uid ) b ON a.uid = b.uid AND a.timestamp = b.max_date jo...
SQL query for to get values from 2 combined table at very fast rate
[ "", "mysql", "sql", "" ]
i am trying to find one column value is present in another table column value. e.g ``` Product_Name(tb_new_purchase) 1.car 2.bus 3.truck Product_Name(tb_new_product_Name_id) 1.car ``` i need to select bus and truck Here is my code ``` SELECT Product_Name FROM tb_new_purchase WHERE NOT EXISTS (SELECT Product_Na...
I know there are already 5 answers here....but just to throw this out here, you can do this as a join and not a where exists. Subqueries can really hinder performance and runtime. In MSSQL, the runtimes should be about the same...is MySQL, this join syntax works far better. ``` Select a.product_name from tb_new_purcha...
Either use `NOT IN` or pass the field into the `NOT EXISTS` ``` SELECT Product_Name FROM tb_new_purchase WHERE Product_Name NOT IN(SELECT Product_Name FROM tb_new_product_Name_id) ``` or ``` SELECT Product_Name FROM tb_new_purchase WHERE NOT EXISTS (SELECT Product_Name FROM tb_new_product_Name_id W...
how to use NOT EXISTS in sql server
[ "", "sql", "sql-server", "" ]
I have a bunch of strings that should have been stored as value pairs but were not. Now I need to replace every other comma with a semicolon to make them pairs. Hoping to find a simple way of doing this, but there might not be one. ex: > -1328.89,6354.22,-1283.94,6242.96,-1172.68,6287.91,-1217.63,6399.18 should be: ...
``` create function f_tst(@a varchar(100)) -- use right size of field returns varchar(100) -- make sure you use the right size of field begin declare @pos int = charindex(',', @a) + 1 ;while 0 < charindex(',', @a, @pos) select @a = stuff(@a, charindex(',', @a, @pos), 1, ';'), @pos = charindex(',', @a, charindex(',', ...
Surely not so simple as you want, but a CHARINDEX/SUBSTRING solution: ``` Declare @input nvarchar(max) = '-1328.89,6354.22,-1283.94,6242.96,-1172.68,6287.91,-1217.63,6399.18' Declare @i int = 0, @t int = 0, @isComma bit = 1 Declare @output nvarchar(max) = '' Select @i = CHARINDEX(',', @input) While (@i > 0) Begin ...
SQL replace every other comma with a semicolon
[ "", "sql", "sql-server", "replace", "" ]
I am trying to write a query that will return the number of "proactive call cases" made by each employee per month as well as the total number of all cases. Essentially, I am looking to return 3 columns; an EmployeeName, a count of the Proactive Calls for that month, and a count of the total calls that month. To try an...
How about something like ``` SELECT OpenedByName AS EmployeeName, SUM(CASE WHEN ProblemType = 17 THEN 1 ELSE 0 END) AS NumberOfProactiveCallsMONTH, COUNT(1) TotalTicketsMONTH FROM Table1 Where OpenDate Between '2/1/2014' and '3/1/2014' GROUP BY OpenedByName ``` The error you received was due to the ...
You can use like this ``` Select a.OpenedByName AS EmployeeName, Count(a.OpenedByName) As NumberOfProactiveCallsMONTH, b.TotalTicketsMONTH AS TotalTicketsMONTH From table1 a INNER JOIN (Select OpenedByName ,Count(OpenedByName) AS TotalTicketsMONTH From table1 Where OpenDate Between '2/1/2014' and '3/1/2014...
SQL Group By statement within subquery
[ "", "sql", "sql-server", "group-by", "subquery", "" ]
I just started learning SQL; I've created a table. Learned insert command and inserted values in 2 rows. However I've inserted null values in 3rd. Now I want to delete the third row which has 2 columns with no values in it. I'm using the following query: ``` delete employee where city=null; ``` It doesn't seem to b...
According **SQL 92** standard many logical operations with *null values* like ``` > null = null and null or null not null ``` should *always return null* (and *never true*). Some DBMS (e.g. Oracle) follow this rule rigorously, some (MS SQL) can have a mode that `null = null` returns *true*, not required ...
You need the `is null` "operator": ``` delete from employee where city is null; ``` This is because in SQL, *nothing* is equal to `NULL`.
How to delete a row in SQL based on a NULL condition
[ "", "sql", "null", "" ]
I am using views for query convenience. The view is a join between three tables, using `INNER JOIN` and `OUTER RIGHT` joins. The overall result set from the view could be 500,000 records. I then perform other queries off of this view, similar to: ``` SELECT colA, colB, colC FROM vwMyView WHERE colD = 'ABC' ``` This q...
Usually, a view is treated in much the same way as a macro might be in other languages - the body of the view is "expanded out" into the query it's a part of, before the query is optimized. So your concern about it first computing all 500,000 results first is unfounded. The exception to the above is if the view is e.g...
When not having a materialized view, the SQL behind your view will always executed when using the view e.g. inside the FROM part. Of course, maybe some caching is possible, but this is depending on your DBMS and your configurations. To see what the database is doing in background your might like to start with using `E...
SQL view performance
[ "", "sql", "sql-server", "sql-view", "" ]
All of the examples I've seen for using `sql.Row`, access return values from queries by **position**:`sql.Rows.scan()` requires a correctly typed variable correctly **positioned** in the `scan()` arguments corresponding to the appropriate column, to retrieve each column value returned, such as in the following example:...
Yes, it is possible to do this without having to manually match up the column positions. There are some third-party libraries you can use to do this, such as [sqlx](https://github.com/jmoiron/sqlx) or [gorp](https://github.com/coopernurse/gorp). I would recommend sticking with one of these instead of rolling your own. ...
The only sane & clean way to do this is to use: <https://github.com/jmoiron/sqlx> Let say you have a Place struct: ``` type Place struct { Country string City sql.NullString TelephoneCode int `db:"telcode"` } ``` You scan it easily: ``` rows, err := db.Queryx("SELECT * FROM place") for ro...
Is it possible to retrieve a column value by name using GoLang database/sql
[ "", "sql", "go", "" ]
I am creating a SQL table to hold transactions: ``` create table dbo.TRANSACTIONS ( Id int identity not null, Amount money not null ); ``` For currency (I am using euros) should I use money, decimal, or numeric? I have seen the three being applied to currency columns so I am not sure anymore. Money would be the...
First of all, Decimal and Numeric have the same functionality ([MSDN info about it](http://msdn.microsoft.com/en-us/library/ms187746.aspx)) To answer the new question money VS decimal, there is already a Stackoverflow question about it: [Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?](https://sta...
[Decimal and Numeric](http://technet.microsoft.com/en-us/library/aa258832(v=sql.80).aspx) are for [almost all purposes](https://stackoverflow.com/questions/1841915/difference-betweeen-decimal-and-numeric), [equivalent](https://stackoverflow.com/questions/759401/is-there-any-difference-between-decimal-and-numeric-in-sql...
Money, Decimal or Numeric for Currency Columns
[ "", "sql", "sql-server", "" ]
I have a table in mysql with birth date column that saved as unix timestamp (bigint). I want to write query like this: ``` SELECT ... as `age` FROM `tableName` ``` And ``` SELECT * FROM `tableName` WHERE ... > 30 ``` When the 3 dots is the function that calculate the age from the birth date. I know about the func...
From MySQL's [date and time functions](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html), we can combine `TIMESTAMPDIFF`, `NOW`, and `FROM_UNIXTIME`. Supposing that `dob` is a Unix timestamp representing date of birth: ``` TIMESTAMPDIFF(YEAR, FROM_UNIXTIME(dob), NOW()) ``` From there, it's simple...
``` SELECT FLOOR((unix_timestamp() - birthday)/(86400*365)) AS age FROM table; ```
Calucate age from birth date in mysql
[ "", "mysql", "sql", "" ]
I have a procedure where a `CURSOR c1` is declared. Then I want to output columns in each role `c1` fetches. ``` FOR rec IN c1 LOOP DBMS_OUTPUT.PUT_LINE (rec.branchno || CHR(9) || rec.street || CHR(9) || rec.city || CHR(9) || rec.postcode); END LOOP; ``` I'm now using `CHR(9)` to output exactly ...
Using `DBMS_OUTPUT` to produce formatted reports is probably the wrong approach. SQL\*Plus is pretty good at producing fixed-width text reports. It's not obvious whether the stored procedure is adding some value (in which case you could have it return a `sys_refcursor` to SQL\*Plus) or whether it would just make more ...
I had the same problem when i used a `CURSOR` within a `PROCEDURE`.I used a similar code as following to solve my problem.Hope,this might help you. ``` DBMS_OUTPUT.PUT_LINE(RPAD(rec.branchno,10)||RPAD(rec.street,20)||RPAD(rec.city,20)||RPAD(rec.city,20)); ``` `RPAD` function actually pads the right-side of an expres...
DBMS_OUTPUT.PUT_LINE: Deciding how many tabs to put according to output length
[ "", "sql", "oracle", "plsql", "dbms-output", "" ]
if I have this sql: ``` SELECT A FROM B WHERE C IN ( SELECT D FROM E ) ``` If my internal select don't return any result (0 rows) my where statement will be true or false? I'm using SQL Server
This is your query: ``` SELECT A FROM B WHERE C IN (SELECT D FROM E); ``` The `where` statement is quite simple. It filters out rows there is no match between `B.C` and `E.D`. By your statement, there is no match, so all rows are filtered out. The query returns no rows. The `where` statement is not "true" or "false"...
Ignore the tables for the moment and think about what this does: ``` SELECT 'Yes' WHERE 1 IN (SELECT 1 WHERE 1=0) ```
Empty IN sql statement
[ "", "sql", "sql-server", "t-sql", "" ]
In my project I have locations of the product, which may look like this: ``` - Location 1 -- SubLocation 1 -- SubLocation 2 - Location 2 -- SubLocation 3 -- SubLocation 4 ``` Imagine a zones with subzones in the facilty. I need to store that in DB and then retrive sometime later, like this: `SubLocation 1 at Locatio...
You can define parent\_id reference FK to another record with id (roots have null parent\_id). To define hierarhy and retrieve all subtree in one query you can define an additional field path (VARCHAR). The field should have full path of ids separated with '\_' In your case SubLocation 5 has the path="2\_4\_5" To re...
Dealing with hierarchical data is difficult in MySQL. So, although you might store the data in recursive tables, querying the data is (in general) not easy. If you have a fixed set of hierarchies, such as three (I'm thinking "city", "state", "country"), then you can have a separate table for each entity. This works an...
How do I store nested locations?
[ "", "mysql", "sql", "database-design", "relational-database", "" ]
Our company has a need to store and compute analytics related to content creation, review/approval and publishing workflow for documents. We are looking at something like Amazon SimpleDB. We will store "events" which correspond to actions that users take in the system. For instance: * [User B] requested [document B] ...
And you would use "Action-Nodes" to model Approval, Publication, Edits so you can connect more than two things to it. For modeling time I'd recommend a ordered list of events or even a time tree: <http://docs.neo4j.org/chunked/milestone/cypher-cookbook-path-tree.html> I create a small GraphGist for you to show it, ch...
In Neo4j's Cypher, you can collect things into buckets with CASE/WHEN and aggregation syntax.
NoSQL - How to generate histograms for ranges of data
[ "", "sql", "nosql", "neo4j", "amazon-simpledb", "" ]
I am trying to extract the text between two characters using t-sql. I have been able to write it where it pulls the information close to what I want, but for some reason I am not getting what i am expecting(suprise, suprise). Could really use alittle help refining it. I am trying to extract part of the table name that ...
Long, but here's a formula using the brackets: ``` Declare @text varchar(200); Select @text='ALTER TABLE [TABLENAME].[MYTABLE] ADD [VIP_CUSTOMER] [int] NULL'; Select SUBSTRING(@text, CHARINDEX('[', @text, CHARINDEX('[', @text) + 1 ) +1, CHARINDEX(']', @text, CHARINDEX('[', @text, CH...
this is a pretty ugly way to get the length, but I've used something like this before: ``` select SUBSTRING(db.Event_Text, CHARINDEX('.', db.Event_Text) + 2, charindex('] ADD',db.Event_Text) - CHARINDEX('.',db.Event_Text)-2)) ``` Give it a try, it may work for you.
Extracting text between two characters in SQL
[ "", "sql", "t-sql", "" ]
I am struggling for a few days with this issue and I can't figure out how can I fix it. I would like to `group by` my table on values `1`,`2`,`3`,`4`,`5` so I have created a ***temporary table*** with this values. Now I have to `INNER JOIN` this table with other tables on `a.value = #myTempTable.num`. BUT `a.value` ...
In order to avoid such error you could use `CASE` + `ISNUMERIC` to handle scenarios when you cannot convert to int. Change ``` CONVERT(INT, CONVERT(VARCHAR(12), a.value)) ``` To ``` CONVERT(INT, CASE WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value) ELSE 0...
If you are converting a varchar to int make sure you do not have decimal places. For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem. ```...
Conversion failed when converting the varchar value 'simple, ' to data type int
[ "", "sql", "sql-server", "t-sql", "group-by", "" ]
I have been trying for a couple of hours to figure this out, but it still does not work.. I have 2 tables: * Prices * Sales The records are something like: Prices ``` product_name price -------------------- Milk 0.80 Cheese 1.00 Bread 1.50 ``` Sales ``` customer_id product_name num...
Use aliases ``` SELECT s.product_name, SUM(number_purchases), price FROM sales S, prices P WHERE S.product_name = P.productname AND customer_id = 80 GROUP BY s.product_name; ``` DBMS - doesn't know wich product\_name get P.S. and I think u have to add price in group by
Your last query is grouping by `customer_id`. Try changing this to `product_name`: ``` SELECT S.product_name, SUM(S.number_purchases), P.price FROM sales S, prices P WHERE S.product_name = P.product_name AND S.customer_id = 80 GROUP BY S.product_name; ``` You should also *never* use commas in the `from` clause. Inste...
MySQL - How to join those tables to get the correct result?
[ "", "mysql", "sql", "" ]
I have this table ``` CREATE TABLE staff ( `id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(32), `surname` varchar(32), `dateEnrollment` date, `dateCompletion` date, PRIMARY KEY (`id`) ); INSERT INTO staff (`firstname`, `surname`, `dateEnrollment`, `dateCompletion`) VALUES ('Demo', 'Demo', '2010-...
Either of the following will work, (I prefer the latter): ``` SELECT MAX(DATEDIFF( (SELECT MIN(s2.dateCompletion) FROM staff s2 WHERE s2.dateCompletion >= s.dateCompletion AND s2.id != s.id) , dateCompletion)) from staff s; ``` In the above example, for each record, you find the next completed project, do ...
Try: ``` SELECT s1.id id1, s1.firstname firstname1, s1.surname surname1, s1.`dateCompletion` dateCompletion1, s2.id id2, s2.firstname firstname2, s2.surname surname2, s2.`dateCompletion` dateCompletion2, datediff( s1.`dateCompletion`, s2.`dateCompletion` ) FROM s...
MySQL get longest gap without activity
[ "", "mysql", "sql", "datediff", "" ]
I have a (SQL Server) table similar to the following: SalesSummary Year | Team | Person | Person Sales | Team Sales/Yr 2013      1          Jim             $10                  ?? 2013      1         Anna            $0                   ?? 2013      2         John             $8                   ?? 2013      3  ...
Assuming you are using SQL Server, I think you want something like this: ``` WITH toupdate AS (SELECT team, year, Sum(personsales) OVER (partition BY team, year) AS newTeamSales FROM salessummary ) UPDATE toupdate SET teamsales = newteamsales; ``` Your original query has several is...
Try this. ``` UPDATE SalesSummary SET TeamSales = (Select Sum(PersonSales) From SalesSummary S Where S.Year=SalesSummary.Year AND S.Team=SalesSummary.Team) ```
SQL How to Update SUM of column over group in same table
[ "", "sql", "sql-server", "optimization", "" ]
I have a SQL query which returns data as listed in table1. I want to compare the column table1.Count with table2.Count\_Range. The range in which the Count value falls in its relevant Value column should be returned. table1: ``` Time Count 2014/02/24 00:00 23.3 2014/02/24 01:00 43.1 2014/02/24 02:00...
You can do this with a correlated subquery: ``` select t1.*, (select top 1 t2.value from table2 t2 where t2.count_range < t1."count" order by t2.count_range desc ) as value from table1 t1; ``` Alternatively, SQL Server offers the `apply` keyword for this sort of thing: ``` select...
Another to do this is to first break the Count Range column into a low value and high value of each range: `Low High Value 0 9 0 10 19 1 20 29 2 30 39 3 40 49 4 50 59 5 ... ... ...` And then using the following query: SELECT Table1.Count, Table2.Value FROM Table2 INNER JOIN Table1 ON Table1.Count >= Table2.LowRange ...
SQL: Compare each record of column with a range of values
[ "", "sql", "sql-server-2008", "" ]
In TSql what is the recommended approach for grouping data containing nulls? Example of the type of query: ``` Select Group, Count([Group]) From [Data] Group by [Group] ``` It appears that the ~~count(\*) and~~ count(Group) both result in the null group displaying `0`. Example of the expected table data: ``` Id,...
The best approach is to use count(\*) which behaves exactly like count(1) or any other constant. The \* will ensure every row is counted. ``` Select Group, Count(*) From [Data] Group by [Group] ``` The reason `null` shows `0` instead of 2 in this case is because each cell is counted as either 1 or null and `null +...
Just do ``` SELECT [group], count([group]) GROUP BY [group] ``` [**SQL Fiddle Demo**](http://www.sqlfiddle.com/#!3/1c284/8) Count(id) doesn't gives the expected result as mentioned in question. Gives value of 2 for group NULL
Count of group for null is always 0 (zero)
[ "", "sql", "t-sql", "" ]
I have a table called list\_details ``` listId tier 1 5 1 5 1 6 2 4 2 5 ``` I want the following result: ``` listId tier 1 5(2), 6(1) 2 4(1),5(1) ``` I tried the following query: ``` SELECT ld.listId,count(ld.tier) from list_d...
I am assuming that you don;t really need the response in the format of `5(2), 6(1)` or if you did need that format for display, you could provide that format in teh application layer. You should simply add multiple groupings: ``` SELECT listId, tier, COUNT(1) AS `tierCount` FROM list_details GROUP BY listId,...
``` SELECT ld.listId, ld.tier, count(ld.tier) FROM list_details ld GROUP by ld.listId, ld.tier; ``` Will yield: ``` list_id tier count 1 5 2 1 6 1 ``` etc
categorize by groupby-SQL
[ "", "mysql", "sql", "" ]
I have an Access 2007 database that will be housing tables which refer to the bill of materials for multiple products. On the main form I want a user to be able to select one of the products - OK, easy. Now, I want two queries to run once they press a button after choosing their product from a dropdown. The first query...
*"... I'm trying to reference the product name in the dropdown on the form as the table name. Please let me know if this is possible."* It is not possible with Access SQL. The db engine can only accept the actual table name --- it isn't equipped to reference a form control to find the table name nor to accept any oth...
So, the user essentially wants 2 queries to run. A `DELETE * FROM Table` query, and an `Append` query. The user wants to know what table to utilize for the `Append` query by using the Combobox (may just be my assumption/interpretation). That being said, why not use something along the lines of: ``` If IsNull(Me.[Combo...
Reference a field on a form within a query using SQL
[ "", "sql", "ms-access", "ms-access-2007", "" ]
I'm having a database with two tables: `users`, `users_addresses` and `countries`. When I'm selecting user record and binding it to the model I'm using the following statement: ``` SELECT `u`.`id`, `u`.`first_name`, `u`.`last_name`, `a`.`address_1`, `a`.`address_2`, `a`.`town`, `a`.`region`, `a`.`post_code`, `a`.`c...
`LEFT JOIN` will include entries from the left table if there's no corresponding entry in the right tables. However in your case you then filter by `a.default = 1` which remove entries with no default address. To avoid that, you will need to either join with a subquery ``` LEFT JOIN ( SELECT * FROM user_adresses ...
Try changing your WHERE clause to this: ``` WHERE (`a`.`default` = 1 OR `a`.`default` IS NULL) AND `u`.`id` = 3 ```
MySQL return record where left joined table has no record
[ "", "mysql", "sql", "left-join", "" ]
i am trying to add incremented values to a new column in table. Here is a sample structure of table ``` --------------------- Name - class - id --------------------- abbc - 2 - null efg - 4 - null ggh - 6 - null --------------------- ``` i want to write a query that will generate unique id's for all rec...
What you have shown should work; the id column should be getting assigned values. I tested your statement; I verified it works on my database. Here's the test case I ran: ``` CREATE TABLE table1 (`name` VARCHAR(4), class TINYINT, id INT); INSERT INTO table1 (`name`,class) VALUES ('abbc',2),('efg',4),('ggh',6); SET @i...
try this query my friend: ``` set @i=0; update table1 set id =(select @i:=@i+1); ``` ## [SQL Fiddle](http://sqlfiddle.com/#!2/73e736/1)
Adding incremented value to new column
[ "", "mysql", "sql", "multiple-insert", "" ]
I have Table `Field1 PK int not null Field2 PK int not null` like this when i want to map this table I get this error ``` Error 3 Error 3034: Problem in mapping fragments starting at lines 2212, 2218: Two entities with possibly different keys are mapped to the same row. Ensure these two mapping fragments map both ...
When i investigate the problem, i realised something becuse i read an article before for this data model situation and i understand the why the problem occur. (Problem in mapping fragments in Entity Framework) Actually problem comes from table mapping because i said that table has many to many relationship so That art...
If nothing else works, try deleting and recreating the whole .edmx-file. I got this problem when I added a couple of many-to-many tables to an existing Entity Framework 6.2 project. I tried removing and regenerating all tables in the model. Nothing seemed to work. I believe there was some "junk" somewhere in the EF pr...
Two entities with possibly different keys are mapped to the same row
[ "", "sql", "entity-framework", "entity-framework-mapping", "" ]
Imagine the following structure: ``` Group Color ColorDesc ----- ----- ----- 1 'Red' 'The cool name of Red Color' 1 'Green' 'The cool name of Green Color' 2 'Blue' 'The cool name of Blue Color' 2 'Yellow' 'The cool name of Yellow Color' 2 'Purple' 'The cool name of Purple ...
``` Declare @t table(Groups int,Color varchar(50),ColorDesc varchar(50)) insert into @t select 1 ,'Red', 'The cool name of Red Color' union all select 1,'Green', 'The cool name of Green Color' union all select 2,'Blue', 'The cool name of Blue Color' union all select 2,'Yellow', 'The cool name of Yellow Color' ...
Try like this ``` SELECT DISTINCT Group, STUFF(( SELECT ',' + Color FROM Table1 S WHERE T.Group = S.Group FOR XML path('') ), 1, 1, '') [GroupedColor] FROM Table1 T ```
How to output a single column or concatenate another one if multiple rows are in group in T-SQL
[ "", "sql", "sql-server", "t-sql", "sqlclr", "" ]
How can I avoid having to type the same `CASE WHEN...` over and over in a `WHERE` clause? `CASE WHEN rawGlass.blockHeight > rawGlass.blockWidth THEN rawGlass.blockWidth ELSE rawGlass.blockHeight END` repeats quite frequently in this query. I'd like to only have to do that once. I already know referencing `[Glass Heigh...
Use CROSS APPLY ``` SELECT pgwName AS [Part Name], active AS [Active], boardName AS [Vinyl Board], rollWidth AS [Roll Width], [Glass Height] FROM parts LEFT JOIN cutVinyl ON parts.vinylBoard = cutVinyl.boardName LEFT JOIN rawGlass ON parts.outerSku = rawGlass.sku CROSS A...
You can choose to write an outer query with current as a sub-query like this: ``` SELECT * FROM ( SELECT pgwName AS [Part Name], active AS [Active], boardName AS [Vinyl Board], rollWidth AS [Roll Width], CASE WHEN blockHeight > blockWidth THEN blockWidth ELSE blockHeight END AS [Glass Height] ...
Avoid Repeated Case When
[ "", "sql", "case", "sql-server-2008-express", "simplify", "" ]
I have a problem with my table in my database. Here's the problem: Why is `'BP99999'` is greater than `'BP100000'` ? Whenever I query where this column is ordered by `DESC` it takes `'BP99999'` as the first row instead of the `'BP100000'` Additional info: my column type is `nvarchar` Do you have any suggestions fo...
Presently the 9 after the BP is greater than 1 resulting in the problem which you are facing. The possible solution is that you need to take out the first 2 characters out of your column value and then do the sorting on the integer value. You may try something like this: ``` SELECT [BProject_ID] FROM [Workload].[db...
``` ORDER BY RIGHT([BProject_ID], LEN([BProject_ID]) - 2) ``` Or simpler ``` ORDER BY SUBSTRING([BProject_ID],2,8000) ```
SQL nvarchar order
[ "", "sql", "sql-order-by", "" ]
I'm using this query to to calculate yearly finance values. ``` select [Year], [FinanceValue-2014], [FinanceValue-2013], [FinanceValue-2012], [FinanceValue-2014]-[FinanceValue-2013] as [FinanceValue Variance] ``` Now I need to multiply the [FinanceValue Variance] \* 2.50 and for that how c...
This can be done using table expressions as below. In any clause of the outer query, you can refer to column aliases that were assigned in the SELECT clause of the inner query. This helps you get around the fact that you can’t refer to column aliases assigned in the SELECT clause in query clauses that are logically pro...
Use CROSS APPLY to create aliases ``` SELECT [Year], [FinanceValue-2014], [FinanceValue-2013], [FinanceValue-2012], [FinanceValue Variance], [FinanceValue Variance] * 2.50 as [NewVariance] FROM Finance CROSS APPLY ( SELECT [FinanceValue-2014]-[FinanceValue-2013] as [...
Use alias name as a column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have two Select queries. The first Select query gives the output which has two columns viz. ``` A B ------ 1 2 3 4 5 6 7 8 ``` The second Select query given the output which as two columns viz Column B and Column C. All the values in Column B of this select statement matches the values of Col...
If you have *elaborated* queries (not just *tables* to join), you may try using `with` construction ``` with Query1 as ( -- <- Put your 1st Query text here select A, B ... ), Query2 as ( -- <- Put your 2nd Query text here select B, C ... ) se...
Consider you tables like having fields like ``` TableA(A ,B) , TableB(B,C) ``` Try using `JOIN` like ``` SELECT TableA.A , TableA.B, TableB.C FROM TableA JOIN TableB ON TableA.B = TableB.B; ```
How to merge(columns) outputs of two SELECT statements in oracle sql?
[ "", "mysql", "sql", "sql-server", "oracle", "" ]
i don't if the title is good but anyway, i was wondering if we can add the sum of a table after summing duplicates with another table just like the following example: Table A: ``` Date BL Client Design Ref1 Ref2 Ref3 Qte 14/01/2013 13011401 A VT VT1 JAUNE ...
You can try using `JOINS` ``` SELECT TableA.Date, TableA.BL, TableA.Client, TableA.Design, TableA.Ref1, TableA.Ref2, TableA.Ref3, TableA.Qte + TableB.Qte As Qte FROM TableA JOIN TableB ON TableA.Client = TableB.Client AND TableA.Design = TableB.Design AN...
I guess this is what you want ``` select t.Date,t.BL,t.Client,t.Design,t.Ref1,t.Ref2,t.Ref3, t.Qte+t1.Qte as qte from table1 t inner join table2 t1 on t.client=t1.client and t.design=t1.design and t.ref1=t1.ref1 and t.ref2=t1.ref2 and t.ref3=t1.ref3; ```
add up the result of the sum of two tables
[ "", "mysql", "sql", "sql-server", "" ]
I need to check whether a variable has a value or not. ``` declare @name varchar(20) set @name = (SELECT Product_Name FROM tb_new_product_Name_id WHERE Product_Name = @productName) if (@name ) // here I need to check it ``` How to do it? thanks
Try this ``` if (@name is null or @value = '') //it will indicate whether it contains a value or not ```
Just do the [`IF`](http://technet.microsoft.com/en-us/library/ms182717.aspx) directly, using [`EXISTS`](http://technet.microsoft.com/en-us/library/ms188336.aspx) instead: ``` IF EXISTS(SELECT * FROM tb_new_product_Name_id where Product_Name=@productName) BEGIN --Do something because a row existed with tha...
How to check if a variable has a value in a SQL Server 2008 stored procedure
[ "", "sql", "sql-server", "" ]
i need to select last inserted row identity value so i tried below code ``` select SCOPE_IDENTITY() from tb_new_product_Name_id ``` but its not showing. where i made error?
There are three similar concepts in MS SQL Server - @@IDETITy, SCOPE\_IDENTITY() and IDENT\_CURRENT(). Here are sample code: ``` CREATE TABLE TestData ( id INT IDENTITY(1,1) PRIMARY KEY, name VARCHAR(25) NOT NULL) INSERT TestData VALUES('one'), ('two') CREATE TABLE TrigData ( id INT IDENTITY(100,5) PRIMARY KEY, nam...
You don't need to specify a table name here.. SCOPE\_IDENTITY() is just a function which returns the recent identity value generated in the current scope.
how to get last inserted identity value
[ "", "sql", "sql-server", "" ]
I want to display records of last 4 months from current date. I don't want to consider time How can I get just date part from the below query? ``` where OrderDate >= DATEADD(month, -4, GETDATE()) ```
Why not use the simple DATEDIFF function ``` where DATEDIFF(MM, OrderDate, GETDATE()) < 4 ```
If you're using SQL Server 2008, try converting `GETDATE()` to a `DATE` directly. ``` WHERE OrderDate >= DATEADD(month, -4, CONVERT(date, GETDATE())) ``` <http://sqlfiddle.com/#!3/df444/2>
How to get only date part while using dateadd() and getdate()
[ "", "sql", "sql-server", "t-sql", "date", "" ]
I have a table called `requests` on which the columns are `id`, `placeId`, `songId`, `userId` `id` is the primary index of the table. Rest of the columns are only unsigned integers and no other unique key is defined. I want `placeId` & `songId` pairs to be unique, i.e., if a row has `placeId` : 5 and `songId` : 12, n...
you can create a UNIQUE index on multiple columns like this ``` CREATE UNIQUE INDEX placeSong ON requests (placeId, songId) ```
Another method is to add an unique constraint to the table : ``` ALTER TABLE requests ADD CONSTRAINT placeSong UNIQUE( placeId , songId ); ```
Using group of columns as a unique key in MySQL
[ "", "mysql", "sql", "" ]
The following are the tables are an example of the issue I am having: **Companies** *{Id}* **CompanyPeople** *{CompanyId, PeopleId}* **People** *{Id}* **PeopleChildren** *{PeopleId, ChildrenId}* **Children** *{Id}* I want to delete all the people of a company and then delete the children of the people. I cannot ...
I would normally use [table variables](http://technet.microsoft.com/en-us/library/ms175010.aspx) or [temp tables](http://technet.microsoft.com/en-us/library/ms174979.aspx) to capture the data to be used first, and then perform the deletes: ``` declare @people table (PersonID int not null) create table #children (Child...
You can delete the children of the people who are in the company you want to delete first by ``` delete from Children where ChildrenID in (select ChildrenID from Children, PeopleChildren, CompanyPeople where Children.ChildrenID = PeopleChildren.ChildrenID and PeopleChildren.PeopleID = CompanyPeople.PeopleID and Compan...
Delete relational join tables
[ "", "sql", "sql-server", "join", "sql-delete", "" ]
Yesterday I was looking at queries like this: ``` SELECT <some fields> FROM Thing WHERE thing_type_id = 4 ``` ... and couldn't but think this was very "readable". What's '4'? What does it mean? I did the same thing in coding languages before but now I would use constants for this, turning the 4 in a THING\_TYPE\_AVAI...
Primary key values should **not** be coded as literals in queries. The reasons are: * Relational theory says that PKs should not convey any meaning. Not even a specific identity. They should be strictly row identifiers and not relied upon to be a specific value * Due to operational reasons, PKs are often different in...
I assume that the question is about the two versions of the query -- one with the numeric comparison and the other with the join and string comparison. Your colleagues are correct that the form with `where thing_id in (list of ids)` will perform better than the `join`. The difference in performance, however, might be ...
Is using JOINs to avoid numerical IDs a bad thing?
[ "", "sql", "oracle", "join", "" ]
I've a table contains the columns like ``` Prefix | CR ---------------------------------------- g | ;#WR_1;#WR_2;#WR_3;#WR_4;# v | ;#WR_3;#WR_4;# j | WR_2 m | WR_1 d | ;#WR_3;#WR_4;# f9 | WR_3 ``` I want to retrieve data from **CR** column WHE...
The easiest way is: ``` select top 1 CR from table t order by len(CR) desc ``` Note that this will only return one value if there are multiple with the same longest length.
You can: ``` SELECT CR FROM table1 WHERE len(CR) = (SELECT max(len(CR)) FROM table1) ``` Having just recieved an upvote more than a year after posting this, I'd like to add some information. * This query gives all values with the maximum length. With a TOP 1 query you get only one of these, which is usually not de...
How to find longest string in the table column data
[ "", "sql", "ms-access", "" ]
There is a table containing all names: ``` CREATE TABLE Names( Name VARCHAR(20) ) ``` And there are multiple tables with similar schema. Let's say: ``` CREATE TABLE T1 ( Name VARCHAR(20), Description VARCHAR(30), Version INT ) CREATE TABLE T2 ( Name VARCHAR(20), Description VARCHAR(30), Version INT ) ...
Well, this is a solution to eliminate the `case` statement and minimize the repetitive part of the query, it requires some joins of it's own of course, so you'd need quite some tables and/or versions to get any real benefit out of it: ``` ;WITH AllDescriptions AS ( SELECT 1 AS Rank, * FROM T1 UNION ALL SELECT ...
Try this query and it will also give you the expected result. ``` SELECT N.name AS Name, Description = CASE WHEN ( t1.description IS NOT NULL ) THEN t1.description WHEN ( t2.description IS NOT NULL ) THEN t2.description ELSE NULL END FROM...
alternative solution to too many JOINs
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I faced this problem while developing a Trigger in Oracle: [ORA-01403: no data found](http://www.techonthenet.com/oracle/errors/ora01403.php). I did some research and understood the root of the problem. Nevertheless [handling the error exception](http://www.orafaq.com/wiki/ORA-01403) prevents the above error, but does ...
Just populate the field directly, using ordering and `rownum`: ``` SELECT * INTO RESULTROW FROM (SELECT * FROM DATE_REFERENCE ORDER BY (CASE WHEN DATE_GIVEN BETWEEN DATE_START AND DATE_END THEN 1 ELSE 0 END) DESC, (DATE_START - DATE_GIVEN) ) t WHERE ...
I also had similar problem, resolved it like this: if the row does not exists in table `LADDER.INCR_PROCESS` I get `IsPassed` as Null: ``` Declare IsPassed Integer ; Begin Select I.LVL Into IsPassed From LADDER.INCR_PROCESS I Right Join Dual on I.LVL >= 90010 and I.Passed = 0...
Oracle PL/SQL - ORA-01403 "No data found" when using "SELECT INTO"
[ "", "sql", "oracle", "plsql", "triggers", "oracle11g", "" ]
Hitting a record based on multiple where clauses, I would like SQL to return a copy of the row being hit, for every where clause that matches. ``` c1 | c2 | c3 x y z ``` x,y,z : Would be return only once with a `where c1=x or c3=z` I would like `where c1=x or c3=z` , to return, 2 copies of x,y,z Can this be ...
This would do it although it might not be as elegant as you'd like ``` SELECT c1,c2,c3 FROM [MyTableName] where c1=x UNION ALL SELECT c1,c2,c3 FROM [MyTableName] where c3=z ```
Already answered, but here is an alternative: ``` SELECT c1,c2,c3 FROM [MyTableName] JOIN (VALUES (1),(2)) t(n) ON (t.n = 1 AND c1 = 'x') OR (t.n = 2 AND c3 = 'z'); ```
SQL query to return more than one copy of same row, if hit on more than one where clause
[ "", "sql", "sql-server", "search", "search-engine", "record", "" ]
I have one field in SQL Server containing section, township and range information, each separated by dashes; for example: `18-84-7`. I'd like to have this information broken out by each unit, section as one field, township as one field and range as one field, like: `18 84 7`. The number of characters vary. It's not al...
There are probably several different ways to do it, some uglier than others. Here's one: (Note: dat = the string of characters) ``` select *, substring(dat,1,charindex('-',dat)-1) as Section, substring(dat,charindex('-',dat)+1,charindex('-',dat)-1) as TownShip, reverse(substring(reverse(dat),0,charindex('-',rev...
Please try more reliable code CREATE BELOW FUNCTION ``` CREATE FUNCTION dbo.UFN_SEPARATES_COLUMNS( @TEXT varchar(8000) ,@COLUMN tinyint ,@SEPARATOR char(1) )RETURNS varchar(8000) AS BEGIN DECLARE @POS_START int = 1 DECLARE @POS_END int = CHARINDEX(@SEPARATOR, @TEXT, @POS_START) WH...
How to Split String by Character into Separate Columns in SQL Server
[ "", "sql", "regex", "sql-server-2008-r2", "" ]
I want to find a female who has visits to two or more restaurants. Here are the tables. Cust: ``` Name | Gender -------------- sarah | female Tim | Male ``` Visits: ``` Name | Restaurant ------------------ sarah | Crab City Tim | Domino's sarah | Crab City sarah | Krusty City Tim | Domino's sarah | Crab Ci...
``` SELECT Temp_Table.name AS NameOfPerson FROM (SELECT cust.name, Count(DISTINCT restaurant) AS UniqueRest FROM visits, cust WHERE cust.name = visits.name AND cust.gender = 'female' GROUP BY cust.name) AS Temp_Table WHERE UniqueRest >=...
You can try something as shown below. The gist of it is to join on a subquery where you use group by/having to only return the >2 visit customers ``` select name from Cust INNER JOIN ( SELECT Name, Restaurant, COUNT(DISTINCT Restaurant) AS UniqueRest ...
How to find fields with calculating other fields?
[ "", "sql", "ms-access", "" ]
I have a ASP.net C# Cloud application and I need to encrypt my SQL Azure Tables. I have researched about this and I found out that SQL Azure doesn't support encryption and that you have to do it in the application layer. Now I have no problem encrypting my stored procedure parameters and decrypting them again when i r...
The only realistic way to have encryption-at-rest in SQL Server in Azure is to provision an IaaS VM with full SQL Server installed, [as described here](http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-provision-sql-server/). Then you can configure whatever full-blown SQL features you want, incl...
In case anyone else stumbles on this question, note that Azure SQL Database now supports Transparent Data Encryption (TDE, aka "encryption-at-rest"). See: <https://msdn.microsoft.com/en-us/library/dn948096.aspx>
ASP.net C# SQL Azure Encryption
[ "", "sql", "azure", "encryption", "azure-sql-database", "" ]
The query below is failing unexpectedly with an arithmatic overflow error. ``` select IsNull(t2.val, 5005) from( SELECT 336.6 as val UNION ALL SELECT NULL ) as t2 ``` "Arithmetic overflow error converting int to data type numeric." Strangely if the query is modified to remove the NULL and replace it with the same...
Try doing this ``` select * into t2 from( SELECT 336.6 as val UNION ALL SELECT NULL ) as x ``` If you now look at the columns, you see a numeric with numeric precision of 4 and scale of 1 ``` select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='T2' ``` SQL made that decision based on the smallest...
I think the problem is that when SQL Server resolves the union, it decides on a decimal type that is only large enough to fit 333.6 (which is `decimal(4,1)`). Trying to put 5005 into that results in an overflow. You can get around that specifying the precision of decimal yourself: ``` select IsNull(t2.val, 5005) from...
Why does this SQL query fail
[ "", "sql", "sql-server", "" ]