Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have an sql query to select randomly 1200 top retweeted tweets at least 50 times retweeted and the tweetDate should be 4 days older from 40 million records. The query I pasted below works but It takes 40 minutes, so is there any faster version of that query? ``` SELECT originalTweetId, Count(*) as total, tweetC...
You are, of course, summarizing a *huge* number of records, then randomizing them. This kind of thing is hard to make fast. Going back to the beginning of time makes it worse. Searching on a null condition just trashes it. If you want this to perform reasonably, you *must* get rid of the `IS NOT NULL` selection. Other...
You're selecting a huge number of records by selecting every record older than 4 days old.... Since the query takes a huge amount of time, why not simply prepare the results using an independant script which runs repeatedly in the background.... You might be able to make the assumption that if its a retweet, the orig...
query optimization to find random sample
[ "", "mysql", "sql", "random", "" ]
I have a table with a column date but it is stored as text. Now I need to extract data based on date and I'm thinking I need to alter the column type to datetime, but how can I do that without losing data? My text records are in format dd-MM-YYYY hh:mm If I just change the column type the data I lose all data (it is ...
``` UPDATE `table` SET `column` = STR_TO_DATE(`column`,'%d-%M-%Y %h:%i') ``` Just change the format to what you have,in case that is not correct. [Formats](http://www.w3schools.com/sql/func_date_format.asp) [**SQL fiddle**](http://sqlfiddle.com/#!2/e8b4f/1)
You can create a new column of type `DATETIME` then you update it with your converted data from your `TEXT` column using the datetime conversion functions from mysql. After update this field youe can change your old field with the data from the new field then drop the field created for store the temp data.
MySQL alter table and convert data from text to datetime
[ "", "mysql", "sql", "date", "datetime", "" ]
I have two tables and I want to update by joining them. I am using DB2 V9.7. **ORDER\_APPROVALS** ``` ORDER_ID CREATED_BY_ID CREATED_BY_NAME PROCESS_DT ------------------------------------------------------- 234 2 admin (null) 307 2 admin ...
You are looking for the [`MERGE`](http://pic.dhe.ibm.com/infocenter/db2luw/v9r7/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0010873.html) statement: ``` merge into ORDER_ATTRIBUTE ot using (select ORDER_ID, CREATED_BY_NAME from ORDER_APPROVALS where PROCESS_DT is null) oa on (ot.ORDE...
I think you need to use a derived table to accomplish this: ``` update order_attributes set value = ( select created_by_name from( select created_by_name, oa.order_id from order_approvals oa left outer join order_attributes ot on oa.order_id = ot.order_id AND OT.ATTRIBUTE_ID =...
How to update DB2 table with a join?
[ "", "sql", "db2", "sql-update", "" ]
**I have a table like this:** ``` ID_____PostingDate_____PosterID -------------------------------- 1______05/01/2012______450 2______06/30/2012______451 3______02/17/2013______451 4______12/10/2012______451 5______06/14/2012______452 6______06/15/2012______452 7______05/01/2012______453 8______06/04/2012______453 9___...
Try this: ``` SELECT DISTINCT PosterID FROM table1 WHERE PostingDate BETWEEN '2012-05-01' AND '2012-06-30' AND posterID NOT IN (SELECT PosterID FROM table1 WHERE PostingDate > '2012-07-01'); ``` `sqlfiddle demo`
``` SELECT PosterID FROM ( SELECT PosterID, MAX(PostingDate) AS latest_post FROM tbl GROUP BY 1) latest_posts WHERE latest_post BETWEEN '2012-05-01' AND '2012-06-30' ORDER BY PosterID; ```
MySQL - Pulling List Pending on Dates
[ "", "mysql", "sql", "unique", "" ]
I have a student table and a company table. **Student Table** id fname lname company\_id **Company Table** company\_id name type I want to output the student table data and then join the company data so the company id will reference the company name and industry. **Here's the query I'm running** ``` SELECT ...
``` SELECT student_id, student_fname, student_lname, company.company_id, company_name, industry FROM `student` INNER JOIN company ON student.company_id=company.company_id ORDER BY industry ``` Specify columns for both tables when you join them.Without them you do a CROSS JOIN,thats is every row in A is associated wi...
It should be `ON student.company_id = company.company_id` Other than that it looks fine. ``` SELECT student_id, student_fname, student_lname, company.company_id, company_name, industry FROM `student` INNER JOIN company ON student.company_id = company.company_id ORDER BY industry ```
SQL Query - join help (Getting lots of results)
[ "", "sql", "join", "" ]
``` select MAX (cast (id as numeric)) from table --whatever value it may return select (row_number () over (order by id)) as Number from table --will start at 1 ``` How do I combine the two so whatever value the first query returns, I can use that value and auto increment from there, somehow combining the two (tri...
Try this: ``` SELECT Seed.ID + ROW_NUMBER() OVER (order by T.ID) as Number, T.ID FROM T CROSS JOIN (SELECT MAX(ID) AS ID FROM T) AS Seed ``` Working sample: <http://www.sqlfiddle.com/#!3/a14ad/3>
Try this: ``` WITH CTE as (SELECT max(Field) FROM Table) SELECT WhatYouWant, cte.m FROM Table2 INNER JOIN CTE ON 0=0 ``` or this: ``` SELECT *, t.maxField FROM Table1 OUTER APPLY (SELECT max(Field) as maxField FROM Table2) t ```
How do I auto increment my own results column from a max value in a table?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I am having trouble finding an answer to this one, so hoping someone may be able to help. I am trying to do the following. I have a table with 4 columns and 22000+ records. Of these 22000+ records, there are 335 distinct server hostnames. Each record represents a peak value of a given metric and the date that correspo...
``` with cte as ( select hostname, metric, peak_d, peak ,row_number() over(partition by hostname order by peak desc) as OrderWithinGroup from Table1 ) select hostname, metric, peak_d, peak from cte where OrderWithinGroup = 1 order by hostname; ```
``` SELECT t1.HOSTNAME, t1.METRIC, t1.PEAK_D, t1.PEAK FROM Table t1 JOIN ( SELECT HOSTNAME, MAX(PEAK) AS MaxPeak FROM Table GROUP BY HOSTNAME ) t2 ON t1.HOSTNAME = t2.HOSTNAME AND t1.PEAK = t2.MaxPeak ```
SQL - Peak value per group from single table
[ "", "sql", "sql-server", "" ]
I made a table of data points - they have a key (type of data), value (value of data), timestamp (time data was recorded). Table definition: ``` CREATE TABLE IF NOT EXISTS datapoints ( point_id int(11) NOT NULL AUTO_INCREMENT, point_user_id int(11) NOT NULL, point_key varchar(32) NOT NULL, point_value longtex...
The following index satisfies your where clause: ``` datapoints(point_key, point_user_id, point_timestamp); ``` This will probably improve the performance of your query significantly, but it won't remove the file sort. The following could, theoretically: ``` datapoints(point_key, point_user_id, point_value, point_t...
`Filesort` will not disappear while you are sorting on point\_value. `point_value` is indexed just 64 bytes. sorting is done by whole it's data. I suggest that store `point_value_64_prefix` for search and sort `point_value` this also has a problem. Sort are done only 64 bytes, sort result is not exactly. but in most c...
How to avoid filesort in this simple query? (No joins)
[ "", "mysql", "sql", "" ]
In my SQL query I need to do some arithmetic on alias. ``` SELECT MY_COMPLEX_EXPRESSION_USING_SUM_AND_CASEWHEN AS MYALIASNAME1, MY_SECOND_COMPLEX_EXPRESSION_USING_SUM_AND_CASEWHEN AS MYALIASNAME2, MYALIASNAME1 - MYALIASNAME2 AS MYALIASHNAME3 FROM MYTABLE ``` However, this does not work because it...
try this. ``` SELECT X.MYALIASNAME1 - X.MYALIASNAME2 AS MYALIASNAME3 FROM ( SELECT MY_COMPLEX_EXPRESSION_USING_SUM_AND_CASEWHEN AS MYALIASNAME1, MY_SECOND_COMPLEX_EXPRESSION_USING_SUM_AND_CASEWHEN AS MYALIASNAME2 FROM MYTABLE )X ```
Use *Common Table Expressions*: ``` with cte as ( select MY_COMPLEX_EXPRESSION_USING_SUM_AND_CASEWHEN AS MYALIASNAME1, MY_SECOND_COMPLEX_EXPRESSION_USING_SUM_AND_CASEWHEN AS MYALIASNAME2 from table ) select MYALIASNAME1 - MYALIASNAME2 AS MYALIASHNAME3 from cte ```
Doing arithmetic on alias in SQL
[ "", "sql", "alias", "h2", "" ]
I need to get a list of months that are not located inside the database. ***Example:*** Table **members** ``` ID | Member's code | Member since 1 | 555-12 | 2012-11-22 ``` Table **membership** ``` ID | Code | Paid 1 | 555-12 | 2013-1-1 2 | 555-12 | 2013-3-12 3 | 555-12 | 2013-5-1 ``` Let's say t...
My idea is to use a number table, that contains just numbers from 0 to 100 or more: ``` CREATE TABLE numbers ( n INT ); INSERT INTO numbers (n) VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15)...; ``` Then you can use a query like this: ``` SELECT m.ID, m.Code, DATE_FORMAT(m.Memb...
``` select code, left(since,7) as debt from user where code='555-12' union all select code, left(date_add(paid, interval -1 MONTH),7) as debt from paid where code='555-12' ``` **Fiddle** <http://sqlfiddle.com/#!2/3d988/1>
Months calculations inside stored procedure
[ "", "mysql", "sql", "date", "stored-procedures", "" ]
I want to simply execute a SQL query that would return the current id of the row that was added to a table, example: ``` insert into V_Post output inserted._ID values('Please return the id of THIS row :)') ``` That shall returns a number like 155 So the aim of my question is to store that number in some kind of loca...
**IDENTITY COLUMN** If it is an identity column and you are only inserting a single row then you can use `SCOPE_IDENTITY()` function to get the last generated Identity value within the scope of the current session. ``` DECLARE @NewValue INT; insert into V_Post values('Please return the id of THIS row :)') SET @NewVa...
You can use `SCOPE_IDENTITY()`: ``` insert into V_Posts values(1, SCOPE_IDENTITY(), null, GETDATE(), null, null, 1) ``` It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value. You can find [here](http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scop...
Store the value of output inserted._ID to local variable to reuse it in another query
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table name farmer data and it has attributes like farmer name, father name, pesticides, variety of crop etc (these attributes would be required for query). I have to write a query for: > Total no of people who has taken more than 1 variety of crop in a Season. How can i write this query? I have tried this q...
Can you try this? ``` select count(*) from (select 1 as y from farmer data group by farmer Name having count(distinct Variety Of Crop)>1) x ```
I believe you are looking for records where Farmers has more the One type of crop. The way you are Counting rows will give you all the farmers who has more than one record regardless of type of Crop using distinct will return list of farmers who has more than one Distinct variety Of Crop. ``` select Farmer Name, Count...
sql query, total number of people who have taken more than 1 variety in a season
[ "", "sql", "sql-server", "" ]
To find out the Nth max sal in oracle i'm using below query ``` SELECT DISTINCE sal FROM emp a WHERE ( SELECT COUNT(DISTINCE sal) FROM emp b WHERE a.sal<=b.sal)=&n; ``` * But According to me by using the above query it will take more time to execute if table size is big. * i'm trying to use t...
try this ``` select * from ( select sal ,dense_rank() over (order by sal desc) ranking from table ) where ranking = 4 -- Replace 4 with any value of N ```
``` SELECT sal FROM ( SELECT sal, row_number() OVER (order by sal desc) AS rn FROM emp ) WHERE rn = 3 ``` Yes, it will take longer to execute if the table is big. But for "N-th row" queries the only way is to look through all the data and sort it. It will be definitely much faster if you have an index on sal.
Nth max salary in Oracle
[ "", "sql", "oracle", "oracle11g", "" ]
`tbl_LoanSummary` has `Sample_Number` column. I have to check if `Sample_Number` column is not null the return 'Y' otherwise return return 'N' from below select statement. ``` select a.Br_Loan_No ,a.Br_LookupKey, //return IsNull(s.Sample_Number) ='N' or 'Y' from dbo.tbl_Br a left outer...
You can use the `case` expression for this... ``` select a.Br_Loan_No, a.Br_LookupKey, CASE WHEN s.Sample_Number IS NULL THEN 'N' ELSE 'Y' END AS [HasSample] from dbo.tbl_Br a left outer join dbo.tbl_LoanSummary s on s.Loan_no = a.Br_Loan_No order by a.Br_Loan_No ```
You'll want to use a `CASE` expression. It's like an embedded if-statement or switch-statement from traditional programming languages. ``` SELECT a.Br_Loan_No, a.Br_LookupKey CASE WHEN s.Sample_Number IS NULL THEN 'N' ELSE 'Y' END AS sample_number_is_not_null FROM dbo.tbl_B...
Return 'Yes' or No' from select statement?
[ "", "sql", "t-sql", "" ]
I have model `waypoint` with two attributes 1. coordinates 2. geocode\_text And model `route` that is no more than sorted array of waypoints with some additional text info. Some routes can have same waypoints, so I want to separate waypoints from routes. What is the best way to store waypoints inside route? I see s...
I'd opt for the second option -- use a join table (RouteWaypoints) with something like acts\_as\_list so that you can retrieve the Route with all it's Waypoints correctly sorted. This isn't overkill -- the DB is *really good* at this stuff.
Those several ways are both viable in your situation. So, to help you, I would just give you the pros and cons of serialization. Then, you'l be able to make a choice * First, freshly new grad, I was taught to not break the [1NF](http://en.wikipedia.org/wiki/First_normal_form). If you choose serialization you'll have...
How to store array in attribute of ActiveRecord model?
[ "", "mysql", "sql", "ruby-on-rails", "activerecord", "many-to-many", "" ]
Thanks you for looking.I am new to tsql and dont know how to proceed. I have a table with 10 different companies and 20 department for each(the departments are same for all the companies). I am trying to calculate percentage of expenses for each department and want an extra column 'Percentage' to be displayed in the re...
I think the clearest way is to use window functions. If you want the percentages based on the `Total%` columns, then you can do it as: ``` select ID, Company_name, Department, Expenses, (100.0* Expenses / max(case when Department like 'Total%Expenses' then Expenses end) over (partition by Co...
Add this column to the query Expenses \* 200.0 / SUM(expenses) over (partition by company\_name) as PercentageExepenses You have to multiply expenses by 200.0 to take into account that you already have the total for the company and therefore double count.
how to find percentage without calculating manually?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "plsql", "" ]
Suddenly, all of sql server requests showing "System.ComponentModel.Win32Exception: The wait operation timed out". What is the quickest way to find the issue? ``` Stack Trace: [Win32Exception (0x80004005): The wait operation timed out] [SqlException (0x80131904): Timeout expired. The timeout period elapsed prior ...
Here how I was able to find the issue, First check all open transaction your database, ``` DBCC OPENTRAN ('Databse') ``` If there is an open transaction then Grab it's SPID and put it inside INPUTBUFFER ``` DBCC INPUTBUFFER (58) ``` This will give you the actual SQL. If you want,you can kill this transaction, ``` ...
Try to execute this command: ``` exec sp_updatestats ```
Currently, All my SQL Request showing "System.ComponentModel.Win32Exception: The wait operation timed out"
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a table in my database of type nvarchar(50); I want to write to that specific column that string 'Tal' - Tal between 2 apostrophes. When I'm trying to do so what is recorded in my DB is "Tal" - Tal between 2 quotation marks. My database is an SQL database and so are my scripts. How this can be solved?
The standard way to do what you want is this. ``` insert into mytable ( mycolumn ) values ('''Tal'''); ``` The first and last `'` are the start and end markers for the string. Each `''` within these characters means `'`. Refer to page 89 of the SQL 92 specification at <http://www.andrew.cmu.edu/user/shadow/sql/sql19...
I think escaping is the key to your question. For SQL apostrophes are special characters, thus they have to be escaped by '' (two apostrophes). Have you checked that your scripts do not add the second apostrophe for you? Probably you have to add *Tal* without the apostrophes. Escape % seems to be DB dependant. Oracles...
how to write a word to a database that is between 2 Apostrophes?
[ "", "sql", "database", "" ]
I have a table called tblAccounts whose contents will come from an excel spreadsheet. I am using MS SQL Server 2008 (x64) on a Windows 8.1 (x64) I tried using the SQL Server Import/Export Wizard but there is no option to choose an existing table but only an option to create a new one. I tried using other methods suc...
Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into...
You can copy-paste data from en excel-sheet to an SQL-table by doing so: * Select the data in Excel and press Ctrl + C * In SQL Server Management Studio right click the table and choose Edit Top 200 Rows * Scroll to the bottom and select the entire empty row by clicking on the row header * Paste the data by pressing C...
Import Excel Spreadsheet Data to an EXISTING sql table?
[ "", "sql", "sql-server", "excel", "sql-server-2008", "import", "" ]
I am using SQL Server 2008 R2. I have a table in which I have a column that have a not null constraint. Now, what if I want to check if column has not null constraint defined or not for specific column? Is there any query to find out it? Thanks in advance..
``` SELECT * FROM INFORMATION_SCHEMA.COLUMNS ``` This query will show all columns from all tables and a whole host of information on them. The column you would want is: `IS_NULLABLE` that can have the value 'YES' or 'NO' [COLUMNS (Transact-SQL)](https://learn.microsoft.com/en-us/sql/relational-databases/system-in...
Something like ``` SELECT o.name AS tab, c.name AS col, c.is_nullable FROM sys.objects o INNER JOIN sys.columns c ON c.object_id = o.object_id WHERE o.name like '%yourtable%' and type = 'U' ``` See [sys.columns](http://msdn.microsoft.com/en-us/library/ms176106.aspx) and [sys.objects](http://msdn.microsoft.com/en-us/...
How to check if a column has not null constraint?
[ "", "sql", "sql-server-2008", "sql-server-2008-r2", "" ]
So i have a small amount of SQL below. ``` SELECT DISTINCT Id, Date, Name_Detail, (SELECT CASE WHEN (Name_Detail IN ('a1','a2') and Name_Detail IN ('d1','d2')) THEN 'AUX' ELSE (CASE WHEN Name_Detail IN ('d1','d2') THEN 'DIN' ELSE ...
For these exact conditions with fixed values (a1,a2,d1,d2) here is a query: `SQLFiddle demo` ``` select ID, max(DATE), CASE WHEN MIN(Name_Detail)in('a1','a2') and MAX(Name_Detail)in('d1','d2') THEN 'AUX' WHEN MIN(Name_Detail)in('d1','d2') ...
I am not sure what you are trying to do, your third rule violates first and second rule, here i have the modified query. ``` SELECT DISTINCT Id, Date, Name_Detail, (SELECT CASE WHEN (Name_Detail IN ('a1','a2') and Name_Detail IN ('d1','d2')) THEN 'AUX' ELSE (CASE ...
Selecting a specific value from multiple unique rows when a single value is different
[ "", "sql", "select", "duplicates", "unique", "rows", "" ]
Each time i want to process 5000 records like below. First time i want to process records from 1 to 5000 rows. second time i want to process records from 5001 to 10000 rows. third time i want to process records from 10001 to 15001 rows like wise I dont want to go for procedure or PL/SQL. I will change the rnum values...
Each query will take a long time because each query will have to join then sort all rows. The `row_number` analytic function can only return a result if the whole set has been read. This is highly inefficient. If the data set is large, you only want to sort and hash-join once. You should fetch the whole set once, usin...
How many unique MARK\_ID values have you got in TABLE\_A? I think you may get better performance if you limit the fetched ranges of records by MARK\_ID instead of the artificial row number, because the latter is obviously not sargeable. Granted, you may not get exactly 5000 rows in each range but I have a feeling it's ...
Want to process 5000 records from the select query is taking long time in oracle database
[ "", "sql", "oracle", "oracle10g", "oracle-sqldeveloper", "database-performance", "" ]
This query is returning more than one row: ``` SELECT T.Title FROM Titles T WHERE T.ArtistID = (SELECT A.ArtistID FROM Artists A WHERE A.Country = "USA"); ``` Is it because it is ambigious?
No, its because there is more than one artist in the USA. What do you want? All the titles written by authors in the USA?? Or all the titles for one specific Author? If you want all the titles written by authors in the USA, ``` Select title from Titles Where ArtistId In (Select ArtistID From artists ...
It means that you have more then one artist with country = 'USA' You can fix it like this to return just any title from any artist from USA ``` SELECT T.Title FROM Titles T WHERE T.ArtistID = (SELECT TOP 1 A.ArtistID FROM Artists A WHERE A.Country = "USA"); ``` if you want all title with artists from USA use JOIN ...
Subquery returns more than 1 row SQL
[ "", "sql", "" ]
In my database in table\_a every row has a date\_created like "2011-04-17" Now some of these dates are in the past, but my question is how can I retrieve the latest date that has not yet passed?
Try this one ``` SELECT * FROM table_a WHERE CURDATE() <= date_created ``` [**CURDATE()**](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_current-date) > Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD > format, depending on whether the function is used in a string or >...
IF date\_created is a date datatype then you can use ``` SELECT * FROM table_a WHERE date_created >= NOW() LIMIT 1 ```
MYSQL get last date from table that has not yet passed
[ "", "mysql", "sql", "date", "" ]
I am using Postgres 9.3 on MacOSX. I am wondering how I can return multiple values (depending on certain criterion) and use them to populate a column in a list/array like manner? ``` --DUMMY DATA CREATE TABLE tbl ( id VARCHAR(2) PRIMARY KEY ,name TEXT ,year_born NUMERIC ,nationality TEXT ); INSERT INTO tbl(...
Use `GROUP BY` and the aggregate function [`string_agg()`](http://www.postgresql.org/docs/current/interactive/functions-aggregate.html) if you want a text column as result. Or [`array_agg()`](http://www.postgresql.org/docs/current/interactive/functions-aggregate.html) to construct an array. But drop the now redunda...
I believe you should change: ``` RETURNS SETOF another_tbl ``` to: ``` RETURNS TABLE(name TEXT, nationality TEXT, ids VARCHAR[]) ```
Return multiple values and populate column in array like manner
[ "", "sql", "list", "postgresql", "distinct", "aggregate-functions", "" ]
I get an error when I execute the following sql query. ``` SELECT RTRIM(name) AS [Segment Name], growth,groupid AS [Group Id], filename AS [File Name], CAST(size/128.0 AS DECIMAL(10,2)) AS [Size in MB], CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(10,2)) AS [Space Used], CAST(size...
If you see logical order processing of query where clause is evaluated before select. to make it work you need to use derived table concept. ``` 1. FROM 2. ON 3. OUTER 4. **WHERE** 5. GROUP BY 6. CUBE | ROLLUP 7. HAVING 8. **SELECT** ``` <http://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-pha...
You are trying to use a column you have defined to filter in the `WHERE` clause. This column does not exist in the table `sysfiles` If you want you can wrap that `SELECT` in another `SELECT` and do the filtering on the latter `SELECT`. That way the column already "exists".
sql query - Invalid column name
[ "", "sql", "sql-server", "" ]
im creating a Table with this command : ``` create table if not exists Event ( _id long INTEGER AUTO INCREMENT,repeatEvery long ,repeating int ,startTime long ,title text ,primary key (_id) ); ``` also tried id without the \_ prefix, and then i fetch all rows with ``` database.query("Event",null , null, null, null, ...
SQLITE by default adds an INTEGER AUTOINCREMENT for you. Search for ROWID. The creation of a column that replicates this functionality will just be created as an alias to ROWID. I did some more digging around and found out what some of the issues are. First of all, SQLITE is garbage. Here is the correct SQL statement...
From [the sqlite docs](http://www.sqlite.org/faq.html#q1) it looks like the definition should be changed a little. the definition should probably be: ``` create table if not exists Event ( _id INTEGER PRIMARY KEY, repeatEvery long, repeating int, startTime long, title text ); ```
Android Database SQLLite AutoIncrement not incrementing and primary constraint violated
[ "", "android", "sql", "database", "auto-increment", "" ]
``` (SELECT ID_OF, Col, BNT, SUM(size1) As size1, SUM(size2) As size2, SUM(size3) as size3, SUM(size4) as size4, SUM(size5) as size5, SUM(size6)as size6, SUM(size7) as size7, SUM(size8) as size8, SUM(size9) as size9, SUM(size10) as siz...
This looks really familiar... But how about this? ``` SELECT a.ID_OF, a.Col, a.BNT, SUM(a.size1) - SUM(b.size1) As size1, SUM(a.size2) - SUM(b.size2) As size2, SUM(a.size3) - SUM(b.size3) As size3, SUM(a.size4) - SUM(b.size4) As size4, SUM(a.size5) - SUM(b.size5) As size5, SUM(a.size6) - ...
A number of methods exist, depending on your actual logic, but for your given question, I'd say simply JOIN them together using either common table expressions, subqueries or temporary tables and then subtract the size column from the corresponding size column. Something like this: ``` ;WITH T1 AS ( SELECT ID_OF...
Sum and Difference of two SQL query result
[ "", "sql", "" ]
I'm trying to export a SQL Azure database to a `.bacpac` file using the Azure portal. The administrator **username** on my database contains a `*`. When I use it in the username field I get this error. ``` The login name must meet the following requirements: It must be a SQL Identifier. It cannot be a system name, for...
Got it. I can add the user to the `db_owner` role and then the export proceeds without error. ``` EXEC sp_addrolemember 'db_owner', 'gu6t6rdb' ```
This will not work on sql azure. You will need to grant view definition at the database level. (without the ANY keyword) GRANT VIEW DEFINITION TO gu6t6rdb P.S: I hit the exact same issue and this seemed to solve my problem. I also had to do a Grant Execute (but it depends on what your bacpac is applying to the databa...
tSQL to set up user with View Definition permission on SQL Azure
[ "", "sql", "sql-server", "t-sql", "azure", "azure-sql-database", "" ]
I have a query like this: ``` SELECT initials, name FROM employee e, projects p WHERE e.country = p.country ``` Until now, both tables used an abbreviation for the country columns. Like `"SWE"` for Sweden and `"ITA"` for Italy. In the future, the employee table will use names for the country columns. Like "Sweden...
It would be better to have an own country table and the other tables referencing to that. ``` country table ------------- id name abbreviation ```
I'd say the best solution is creating a third table where you match the current abbreviation with the full country name. You can then join both tables on that. ``` CountryTable (countryAbbreviation, countryName) ``` The select would then be something like this: ``` SELECT initials, name FROM employee e JOIN countryT...
Modifying a SELECT query
[ "", "sql", "select", "" ]
I have two tables: table message (holds the creator of a message and the message) **id - creatorId - msg** and a table message\_viewers (tells who can read the message msgId) **msgId - userId** If I create a message as user 1 and send it to user 2 and user 3, the tables will look like this: ``` tbl_message: 1...
I think this might do what you want: ``` SELECT m.* FROM message m INNER JOIN message_viewers mv ON m.id = mv.msgId WHERE m.creatorId IN (1, 2, 3) AND mv.userId IN (1, 2, 3) AND NOT EXISTS ( SELECT 1 FROM message_viewers mv2 WHERE mv2.msgId = mv.msgId AND mv2.userId NOT IN (1, 2, 3) ) AND m...
Try this with join and with IN() clause ``` SELECT * FROM tbl_message m JOIN tbl_message_viewers mv (m.id = mv.msgId ) WHERE m.creatorId IN(1,2,3) AND mv.userId IN(1,2,3) ```
MYSQL: Find all posts between certain users
[ "", "mysql", "sql", "" ]
Can any one explain the below query for getting the 3 maximum salaries? ``` select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where a.sal <= b.sal) order by a.sal desc; ``` Someone suuggested to me the use of the above query to get 3 max. salaries in a table....
``` empid sal =============== 1 300 2 50 3 400 4 200 5 150 ================ select distinct sal from emp a where 3 --outer query >= (select count(distinct sal) from emp b --inner query(correlated) where a.sal <= b.sal) order b...
It's a strange way to do this, but it will work. Basically, for each row of table emp, it counts the number of salaries in this table, which are bigger when given, in the subquery: ``` select count(distinct sal) from emp b where a.sal <= b.sal ``` And if number of such salaries is not bigger than three: ...
Explanation of the query for getting the 3 maximum salaries
[ "", "sql", "oracle", "" ]
I have data in the following format: ![enter image description here](https://i.stack.imgur.com/I5nWR.png) I need to pivot this to get the data as follows. ![enter image description here](https://i.stack.imgur.com/mtvlH.png) Please help!!!
The solution I got is a bit tricky but very dynamic. You should first unpivot your table, and put the data in a temp table, after that I get the columns name for the pivoting and put the result in the **@cols** variable. At the end I create a dynamic sql string to pivot the the temp table that contains my data, so even...
Something like this. In this case you need to have a fixed list of names. ``` SELECT SUM(CASE WHEN Student='Mike' THEN [English Mark] ELSE 0 END) as [Mike English Mark], SUM(CASE WHEN Student='Mike' THEN [Maths Mark] ELSE 0 END) as [Mike Maths Mark], SUM(CASE WHEN Student='Fisher' THEN [English Mark] E...
Query to pivot in SQL
[ "", "sql", "sql-server", "pivot", "" ]
I have a mysql user, whom I want to grant all the READ permission on a db schema. One way is this : ``` GRANT SELECT, SHOW_VIEW ON test.* TO 'readuser'@'%'; ``` Is there a way to group all read operations in grant ?
> If there is any single privilege that stands for ALL READ operations on database. It depends on how you define "all read." "Reading" from tables and views is the `SELECT` privilege. If that's what you mean by "all read" then yes: ``` GRANT SELECT ON *.* TO 'username'@'host_or_wildcard' IDENTIFIED BY 'password'; ``...
``` GRANT SELECT ON *.* TO 'user'@'localhost' IDENTIFIED BY 'password'; ``` This will create a user with `SELECT` privilege for all database including Views.
mysql - How to grant read only permissions to a user?
[ "", "mysql", "sql", "security", "permissions", "readonly", "" ]
--- I am working on a school project in which I have to upload data onto a database hosted on phpMyAdmin. What's confusing me right now is that I see "localhost" at the top of the page and before I even query the database I see "Run SQL query/queries on server "localhost":" Does this mean that I'm hosting a server o...
This exactly means what you assumed. When connected to `localhost`, you are connected to local MySQL server on same machine. Using `webhost330....` you are connected to that remote MySQL server instance, if that is not the name of your own machine. Your own server can be `webhost30.etcetc`. **Edit** If your website i...
To see what "localhost" refers to in terms of MySQL server, you have to look at the URL you are using to connect to the web server. For example, if the URL is ``` http://localhost/phpmyadmin ``` and this instance of phpMyAdmin tells me that the MySQL server is on localhost, this means that the MySQL server is on my ...
How exactly am I accessing the host/server through localhost on phpMyAdmin?
[ "", "mysql", "sql", "database", "phpmyadmin", "" ]
I have a query which returns records according to time like ``` +-------------+--------------+ | RenewalTime | RenewalCount | +-------------+--------------+ | 1 | 2345 | | 2 | 189 | | 3 | 789 | | 4 | 7676 | | 5 | 9876 | | ...
I would convert this RenewTime to 5 minute intervals like this: ``` ((cast(i.modification_date as date) - cast(refill_date as date)) * 24 * 60 /5 ``` Next, I would use the floor function to distinguish one 5 minute group from another: ``` floor((cast(i.modification_date as date) - cast(refill_date as date)) * 24 * 6...
i think that this query can create the thing which you want: ``` select to_char((t1.RenewalTime-1)*5)|| '-' ||to_char(t1.RenewalTime*5) as RenewalTime,RenewalCount from (Select Round((Cast(i.Modification_Date As Date) - Cast(Refill_Date As Date)) * 24 * 60,0) RenewalTime, count(1) RenewalCount from refill,su...
SQL Query for group by on Time Interval
[ "", "sql", "oracle", "group-by", "" ]
Example table: ``` id computer app version build date ---|---------|------|------------|-------|--------- 1 | aaaa1 | app1 | 1.0.0 | 1 | 2013-11-11 09:51:07 2 | aaaa1 | app2 | 2.0.0 | 2 | 2013-11-12 09:51:07 5 | xxxx2 | app1 | 1.0.0 | 1 | 2013-11-13 09:51:07 3 | ccc...
Try like this: ``` SELECT d.id, d.computer, d.app, d.version, d.build, a.installed FROM data d INNER JOIN ( SELECT computer, app, max(DATE) AS installed FROM data GROUP BY computer, app ) a ON a.computer = d.computer AND a.app = d.app WHERE placement = 'xxx' ``` The inner query is getting you the max(date) fo...
Try by casting the Datetime field ``` SELECT id, computer, app, version, build, MAX(cast(date as Datetime)) AS installed FROM data WHERE placement = 'xxx' GROUP BY app, computer,...
MySQL select MAX(datetime) not returning max value
[ "", "mysql", "sql", "max", "" ]
In MySQL, I want to collapse duplicate rows while also retaining a list of user\_id containing those duplicates: ``` user_id message lattitude longitude status img_name ------------------------------------------------------------------------------ 3 hello test multiple 42.0473347 89.45...
``` SELECT GROUP_CONCAT(`user_id` separator ',') as user_ids, message, lattitude, longitude, status, img_name FROM table_name GROUP BY img_name, message; ``` Use the Above query for the relevant result.
Try this: ``` SELECT GROUP_CONCAT(user_id separator ','), message, lattitude, longitude, STATUS, img_name FROM YourTable GROUP BY message, lattitude, longitude, STATUS, img_name ``` `SQLFIDDLE DEMO` You may be able to remove some of the GROUP BY columns. See [here](http://dev.mysql.com/doc/refman/5...
SQL Query for duplicate records, retaining a list of the duplicate id's
[ "", "mysql", "sql", "" ]
I'm getting compile errors with this code using sqlplus. My errors are: > Warning: Procedure created with compilation errors. > > BEGIN point\_triangle; END; > > Error at line 1: ORA-06550: Line 1, column 7: > PLS-00905: object POINT\_TRIANGLE is invalid > ORA-06550: line 1, column 7: > PL/SQL Statement ignored...
``` create or replace procedure point_triangle AS BEGIN FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC) LOOP dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS); END LOOP; E...
Could you try this one: ``` create or replace procedure point_triangle IS BEGIN FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P where P.TEAM = 'IND' group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC) LOOP dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thiste...
Stored Procedure error ORA-06550
[ "", "sql", "oracle", "stored-procedures", "ora-06550", "" ]
I want to return all rows that have a certain value in a column and have more than 5 instances in which a number is that certain value. For example, I would like to return all rows of the condition in which if the value in the column M has the number 1 in it and there are 5 or more instances of M having the number 1 in...
Try this : ``` select * from tab where M in (select M from tab where M = 1 group by M having count(id) > 5); ``` [**SQL Fiddle Demo**](http://sqlfiddle.com/#!3/f05e0/1)
`please try` ``` select *,count(M) from table where M=1 group by id having count(M)>5 ```
Return the query when count of a query is greater than a number?
[ "", "mysql", "sql", "count", "group-by", "having", "" ]
Table structure for table Warehouse ``` CREATE TABLE Warehouse ( wID NUMBER(25) , Location VARCHAR2(70) , Num_Employees NUMBER(25) , Stock NUMBER(25) , PRIMARY KEY (wID) ); CREATE SEQUENCE WAREHOUSE_SEQ START WITH 1 INCREMENT BY 1 NOMAXVALUE; INSERT INTO Warehouse (wID, Location, Num_Empl...
Try this.. ``` SELECT DISTINCT Orders.wID, person.name, Employee.*, Warehouse.wID FROM person INNER JOIN Employee ON person.Id = Employee.EID INNER JOIN Warehouse ON Warehouse.LOCATION = Employee.WORK_LOCATION INNER JOIN Orders ON Orders.wID = Warehouse.wID WHERE Emp...
Problem is your first join: 'FROM person INNER JOIN Orders ON Orders.wID = Warehouse.wID' The table 'Warehouse' is at this point not yet available, but you already mention it in the 'on' part.
Inner Join ORA-00904: invalid identifier
[ "", "sql", "oracle", "" ]
I'm building a database for a baseball team, and one of the tables is for pitching stats. If you know baseball, you know baseball ERA is calculated as (number of earned runs given up / divided by innings pitched) \* 9. In the table, I have separate columns for Innings Pitched, and for Earned Runs, and through an SQL s...
You can do that applying simple math, using `ROUND` function. Lets say `Value` is your column name. ``` ROUND(Value, 0) + (10 * (Value - ROUND(Value, 0)) / 3) ``` Little demo: <http://sqlfiddle.com/#!6/5ad7f/2>
You can use `CASE` as below: ``` declare @x decimal(38,6) = 7.1 select case @x - cast(FLOOR(@x) as decimal) when 0 THEN @x when 0.1 THEN cast(FLOOR(@x) as decimal) + 0.3333 when 0.2 THEN cast(FLOOR(@x) as decimal) + 0.6666 end ``` That will always turn * x.0 to x.0 * x.1 to x.3333 * x.2 to x.6666 where...
Calculating numbers from fields in a database
[ "", "sql", "sql-server", "" ]
I am having an issue with the following query returning results a bit too slow and I suspect I am missing something basic. My initial guess is the 'CASE' statement is taking too long to process its result on the underlying data. But it could be something in the derived tables as well. The question is, how can I speed ...
Just as a clue to the right direction for optimization: * When you do an OUTER JOIN to a query with calculated columns, you are guaranteeing not only a full table scan, but that those calculations must be performed against every row in the joined table. It appears that you can actually do your join to oe\_line without...
It's may not be solvable by any of us without the real stuff to test with. IF that's the case and nobody else posts the answer, I can still help. Here is how to trouble shoot it. (1) take joins and pieces out one by one. (2) this will cause errors. Remove or fake the references to get rid of them. (3) see how tha...
Query taking too long - Optimization
[ "", "sql", "sql-server-2008", "optimization", "" ]
I have table such that : ``` value1 value2 value3 value4 value5 constant 1 2 3 4 5 2 8 2 8 3 5 2 1 5 3 4 5 3 1 2 6 4 5 3 ``` Now what i want to ...
**Intro** The normal way to resolve this question is: chose correct structure. If you have 24 fields and you need to loop dynamically in SQL, then *something went wrong*. Also, it is bad that your table has not any primary key (or you've not mentioned that). **Extremely important note** It is no matter that the way ...
value column is fixed from 1 to 5? if not you need to generate dynamic query. try this: ``` SELECT IF(constant = 1, value1, IF (constant = 2, value1 + value2, IF (constant = 3, value1 + value2 + value3, IF (constant = 4, value1 + value2 + value3 + value4, value1 + value2 + value3 + value4 + value...
Find sum across varying no of columns
[ "", "mysql", "sql", "sum", "" ]
I know you can use COALESCE and ISNULL but I was jut wondering if you could do it with a SELECT case. I had this ``` SELECT (CASE Table.Column WHEN ' ' THEN '1/1/2001' Else Table.Column End),Column2 FROM Table ``` That didn't do anything so I tried: ``` SELECT (CASE Table.Column WHEN NULL THEN '1/1/2001' Else Ta...
You can certainly use the [`is [not] null`](http://technet.microsoft.com/en-us/library/ms188795.aspx) predicate like so: ``` select case when t.Column1 is null then '1/1/2001' else t.Column1 end ,t.Column2 from Table1 as t ``` However, there are functions built specifically for dealing with `null`: > **1.*...
Use `IS` with `NULL` ``` SELECT CASE WHEN Column IS NULL THEN '1/1/2001' ELSE Column END, Column2 FROM Table ```
Can you change the value of a column that is NULL using a CASE?
[ "", "sql", "t-sql", "" ]
I have a query with several left outer joins, for simplicity sake I will just include the two. It looks something like this: ``` SELECT Object.ID, Gloss.name, Gloss.order, Title.name from Object LEFT OUTER JOIN Gloss on Gloss.object_id = Object.ID LEFT OUTER JOIN Title on Title.object_id = Object.ID ``` However, some...
This should do the job: ``` SELECT Object.ID, (SELECT name FROM Gloss G WHERE G.object_id = X.object_id AND G.order = X.ord) AS [GlossName], X.order, Title.name FROM Object LEFT OUTER JOIN (SELECT object_id, MIN(order) ord FROM Gloss GROUP BY object_id) X ON X.object_id = Object.ID LEFT OUTER JOIN Title on Ti...
``` SELECT Object.ID, min(Gloss.name), min(Gloss.order), Title.name from Object LEFT OUTER JOIN Gloss on Gloss.object_id = Object.ID LEFT OUTER JOIN Title on Title.object_id = Object.ID GROUP BY Object.ID,Title.name ```
Multiple Outer joins return top result
[ "", "sql", "sql-server", "outer-join", "" ]
I have a table called `messages` that stores user messages, and the table structure looks like this: Messages: ``` id from_id to_id content 1 1 2 ABC 2 2 1 BCC 3 1 2 EFG 1 4 2 GHJ 2 2 4 MNX 3 15 2 LKH ``` ...
You can do either ``` SELECT DISTINCT LEAST(from_id, to_id) from_id, GREATEST(from_id, to_id) to_id FROM messages; ``` Output: ``` | FROM_ID | TO_ID | |---------|-------| | 1 | 2 | | 2 | 4 | | 2 | 15 | ``` or ``` SELECT from_id, to_id FROM messages GROUP BY LEAST(...
I think you're looking for `DISTINCT` ``` SELECT DISTINCT from_id, to_id FROM messages WHERE to_id=2 ```
group messages - MySQL
[ "", "mysql", "sql", "" ]
Given the following table (and sample data): ``` PK | ClientID | SetID | Title ----------------------------- P1 | C1 | S1 | Title1 P2 | C1 | S1 | Title1 P3 | C2 | S2 | Title1 P4 | C2 | S2 | Title1 P3 | C1 | S3 | Title2 P5 | C1 | S3 | Title2 ``` Assuming a `Set` be...
You may try additional indexed view. For example, a table: ``` create table dbo.Test (PK int, ClientID int, SetID int, Title varchar(50), primary key (PK)) insert into dbo.Test values (1, 1, 1, 'Title1') ,(2, 1, 1, 'Title1') ,(3, 2, 2, 'Title1') ,(4, 2, 2, 'Title1') ,(5, 1, 3, 'Title2') ,(6, ...
If I got the question right I would add another table to link between `SetID` and `Title` which have a `1:1` relation and add a unique index on `ClientID and SetID` ``` CREATE UNIQUE INDEX [Index_Name] ON [dbo].[MyTable]([ClientID ], [SetID]) ```
SQL Server Conditional Unique Index
[ "", "sql", "sql-server", "t-sql", "azure-sql-database", "unique-constraint", "" ]
I'm looking to take the data from the query below (all employees in Seattle) and insert it into a new, blank table with identical columns as my select statement. ``` select e.employee_id, e.first_name, e.last_name, e.email, e.phone_number, e.hire_date, e.job_id, e.salary, e.commission_pct, e.manager_id, e.depart...
If you have an existing table you can do: ``` INSERT INTO ExistingTable (Columns,..) SELECT Columns,... FROM OtherTable ``` From your sql ``` insert into newEmpTable (employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id, department_id) select e.employee...
``` CREATE TABLE SeatleEmployees AS (/* your query here */); ```
Simple SQL Table Insert
[ "", "sql", "oracle", "insert", "" ]
I have SQL\*Plus 12.1 installed on Fedora 19 trying to connect to an Oracle 11g database. I installed the instantclient RPM packages (basic, devel, sqlplus) from [here](http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html). I can successfully connect to other Oracle databases using SQL\*Plus, so I know ...
Couple ideas, in order of likelihood of causing this problem: 1) If your password starts with a non-alphabetic character, surround password with quotes: `user/"password"@service` (note, GUI apps e.g. TOAD and SQLDeveloper don't require quotes). 2) Run ``` > tnsping service ``` And confirm your output matches the tn...
ORA-01017 is pretty clear. It means that you got either the username or password wrong, or possibly that you're not *really* connecting to the database that you think you're connecting to. There's really not much more to say. Double check your connect descriptor, and make sure you didn't mistype the username or passwo...
ORA-01017 error in sqlplus 12.1, can connect with same credentials in other applications
[ "", "sql", "oracle", "oracle11g", "sqlplus", "ora-01017", "" ]
I have a table with 40mil records. I need to add a new INT NOT NULL column to that table, with default value = 0 When adding this column using the following: ``` ALTER TABLE myTable ADD NewColumnID int NOT NULL CONSTRAINT DF_Constraint DEFAULT 0 ``` It sets the NewColumnID to 0 for all records. When running this que...
Thanks Aaron for your detailed approach, but I did a quick test and the simple approach would be to do the following: Some background. I'm adding a CompanyID to an existing large table. The ID refers to the company the record belongs to. Default value would be 0. But since this is going into an existing customers prod...
The major problem is that this needs to write to every single row, which is heavily logged as one single transaction. One way to minimize the impact to the log (and this works best if you don't have silly 10% autogrow settings on your log file) is to break up the work as much as possible: 1. add a NULlable column: ...
Adding column with default value to large table
[ "", "sql", "sql-server", "performance", "" ]
I need to fill a cell with the first non-empty entry in a set of columns (from left to right) in the same row - similar to coalesce() in SQL. In the following example sheet ``` --------------------------------------- | | A | B | C | D | --------------------------------------- | 1 | | x ...
``` =INDEX(B2:D2,MATCH(FALSE,ISBLANK(B2:D2),FALSE)) ``` This is an Array Formula. After entering the formula, press `CTRL` + `Shift` + `Enter` to have Excel evaluate it as an Array Formula. This returns the first nonblank value of the given range of cells. For your example, the formula is entered in the column with th...
I used: ``` =IF(ISBLANK(A1),B1,A1) ``` This tests the if the first field you want to use is blank then use the other. You can use a "nested if" when you have multiple fields.
Is there a coalesce-like function in Excel?
[ "", "sql", "excel", "xls", "coalesce", "" ]
I have these three tables (Soknad, Prognose and Did) in the SQL Server database: Table Soknad has columns: S\_ID (key), S\_REFNR Table Prognose has columns: P\_ID (key), P\_S\_ID Table Did has columns: D\_ID (key), D\_S\_ID, Did\_Something Prognose.P\_S\_ID is foreign key to Soknad.S\_ID. Did.D\_S\_ID is foreign ke...
Here you go: ``` select s.s_id, p.p_id, count(d.Did_Something) as Count_D_Did_Something, -- nulls won't be counted sum(CASE WHEN d.Did_Something = 1 THEN 1 ELSE 0 END) as Count_D_Did_Something_is_one from Soknad as s left join Prognose as p on p.P_S_ID = s.s_id left join Did as ...
I believe what you want to do is join two tables and put the counts where the rows match the left table in separate columns for each table. This would accomplish that. ``` select t1.id, count(t2.id) t2_count , count(t3.id) t3_count from table1 as t1 left outer join table2 as t2 on t2.table1_id = t1.id ...
Join three tables with counts
[ "", "sql", "" ]
I have this SUMIF `=SUMIF(WEZ_ARTICLE_PLANT!A:A,$E2,WEZ_ARTICLE_PLANT!AX:AX)` I want do the same as the sumif in sql excel. In my query ``` WEZ_ARTICLE_PLANT!A:A = column_Material $E2 = column_Material WEZ_ARTICLE_PLANT!AX:AX = column_StockQty ``` I would be glad for any Responce!
you will have to start thinking of things in a slightly different way now that you are working with a database. ``` SELECT column_Material, SUM(column_StockQuantity) FROM YouTableName GROUP BY column_Material ``` will give you a total of all quantities for each *column\_Material*
You mean something like this? ``` Select sum(column_StockQty) from table_Name where column_Material = 'Example' ```
Interpreting SUMIf in excel sql
[ "", "sql", "excel", "formulas", "" ]
I am trying to query a sql server table which has values in upper case and it doesn't return anything. For example, Table structure, ``` ID Fruit -- ------ 1 APPLE ONE 2 ORANGE TWO 3 PEAR THREE Select * from Fruits where fruit = 'APPLE ONE' ``` Does not return anything. But if i change it to "apple one" in ...
You can use the UPPER or LOWER function. Like this: ``` Select * from Fruits where UPPER(fruit) = 'APPLE ONE' ``` Also like op. will ignore case: ``` Select * from Fruits where fruit like 'APPLE ONE' ```
Make sure your column is set to the correct collation. Or you can specify the collation in your query directly. Collations with CI are Case Insensitive. This will return your 'apple one' record: ``` select 'CI', * from table1 where myfield = 'apple one' collate SQL_Latin1_General_CP1_CI_AS ``` This will not return y...
sql server querying values in upper case
[ "", "sql", "sql-server", "" ]
Imagine the following table: ``` prprno prprdt pritcd prqnty popono poqnty ---------- -------- -------- -------- -------- -------- 2013100017 28-10-13 220010284 2000 2013100017 800 2013100017 28-10-13 220010284 2000 2013100018 500 2013100017 28-10-13 220010284 2000 ...
Please try: ``` ;with T as( select *, ROW_NUMBER() over (order by prprno) RNum From YourTable ) select prprno, prprdt, pritcd, prqnty, popono, poqnty, prqnty-(select SUM(poqnty) from T b where b.RNum<=a.RNum) blnce from T a ``` [Sql Fiddle Demo](http://sqlfiddle.co...
You can write this as a correlated subquery: ``` SELECT prprno ,prprdt ,pritcd ,prqnty , popono ,poqnty , (SELECT SUM(T2.poqnty) FROM table1 AS T2 WHERE T2.prprno = T1.prprno --one purchase requisition AND T2.pritcd = T1.pritcd AND T2.popono > t1.popono) AS blnce FROM table1 AS T1 ORDER BY T1.pop...
calculate a running total between two fields in SqlServer 2008
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I want to define the new field in a select into statement as integer. However, the NewField ends up as binary. How can I accomplish this? ``` SELECT ExistingField1, ExistingField2, NewField INTO NewTable FROM ExistingTable ``` I searched a lot but couldn't find a solution yet. Edit 1: I am performing the SELECT INTO...
The reason it ends up as a binary is because the field in the existing table most likely is a binary field. You could try doing something like this: ``` SELECT ExistingField1, ExistingField2, CAST(NewField AS int) INTO NewTable FROM ExistingTable ``` `CAST` does not work in MsAccess. However, this should work: ``` ...
For Access I would use this, then the parameter dialog does not show. ``` SELECT ExistingField1, cInt(0) AS NewField into NewTable1 FROM Table1 ``` For SQL Server ``` CAST(null AS int) AS NewField ```
How to define the type (int) for a new field in SQL SELECT INTO statement in MS Access
[ "", "sql", "ms-access", "select-into", "" ]
I have the following code: ``` create table test.dbo.Users ( Id int identity(1,1) primary key, Name varchar(36) not null ) create table test.dbo.Number ( Id int identity(1,1) primary key, Number varchar(10) not null, Name varchar(36) not null foreign key references Users.Name ) ``` The foreign ke...
Please see in this SQLfiddle link, [Link](http://www.sqlfiddle.com/#!2/3a105/2) ``` CREATE TABLE NUMBER( ID INT PRIMARY KEY, NUMBER VARCHAR(10) NOT NULL, NAME VARCHAR(36) NOT NULL REFERENCES USERS(NAME) ); ```
Foreign key must reference a primary key in another table I would use the following code I hope it is useful ``` use test create table test.dbo.Users ( Id int identity(1,1) primary key, Name varchar(36) not null ) create table test.dbo.Number ( Id int identity(1,1) primary key, Number varchar(10) no...
Foreign key references invalid table
[ "", "sql", "" ]
I have to write an SQL SELECT statement which is valid for MS SQL Server and Oracle. I have to work with old customer databases, so I cannot change anything in the db design... Problem is that the table has a nullable column 'project' which is a varchar that is in some cases filled with an empty string - which is tran...
Because the condition `'' = ''` will be true only in SQL-Server (it's equivalent to `'' IS NOT NULL`) and the condition `'' IS NULL` will be true only in Oracle, you can use this: ``` WHERE ( project > '' AND '' = '') -- for SQL-Server OR ( project IS NOT NULL AND '' IS NULL) -- for Oracle ``` Note...
You can use `NULLIF()`, which is available in both [SQL Server](http://technet.microsoft.com/en-us/library/ms177562.aspx) and [Oracle](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions107.htm#SQLRF00681) (it's part of the ANSI standard). ``` select * from table where nullif(project, '') is not null ``...
Oracle empty string/NULL
[ "", "sql", "sql-server", "oracle", "" ]
I have the following **MySql** table: ``` mysql> describe drft1_menu; +-------------------+---------------------+------+-----+---------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+---------------------+------+-----+-...
For only one column (or similar-named columns) you can use: ``` SHOW FIELDS FROM `drft1_menu` LIKE 'id' ``` -for `id` column. But that may not answer the question in common case. For that there's `INFORMATION_SCHEMA` database (sample below for columns `id`, `title`): ``` SELECT * FROM INFORMATION_SCHEMA.colum...
Select id, title, alias from drft1\_menu
How to specify to show only some specifics field in a select * query output in MySql?
[ "", "mysql", "sql", "database", "" ]
I have two tables, with size 1TB each and are considered contains same data. However, when I use them the same way, the results differs. So, I would like to compare them record by record, in order to find out what's the difference. --- My current solution is an ugly one: I ordered them by the same key, output th...
Is it two copies of the same data? If so can you join the tables and select out the differences? [SQLFiddle](http://sqlfiddle.com/#!6/0f035/5) Quick example: ``` create table atable ( id int, field1 int, field2 varchar(16) ) create table btable ( id int, field1 int, field2 varchar(16) ) select * fr...
You could try hashing the rows of table 1 using any hash function and then run through table2 to see if there is any entry which is not already hashed. Theoretically it will be most efficient solution I guess. You could use minhash/ LSH hash functions for scaling up.
Fastest way to compare if two tables have exactly the same contents
[ "", "sql", "hadoop", "hive", "" ]
I have a table like this: ![My table](https://i.stack.imgur.com/wnexw.jpg) I like to get something like this: ![My Result Table](https://i.stack.imgur.com/A5Fpu.jpg) The rows starting with 'Property' will go to Property column. Rows starting with 'Location' will go to 'Location' column, and rows starting with 'erro...
This can be done in 1 query. First split the data into three parts (Property, Location and Error) and determine the Parent ID's. Finally, use regular joins to create the result: ``` with P as ( select ID, ColumnDesc from MyTable P where columnDesc like 'Property %' ), L as ( select ID, ColumnDesc, (Select MAX...
Interesting problem in my opinion. Here's a solution in Oracle. I think it's the shortest one posted so far, just using a single query with two sub-queries. ``` WITH data1 AS ( SELECT 1 AS id,'Property X' AS columnDesc FROM DUAL UNION SELECT 2 AS id,'Location abc' FROM DUAL UNION SELECT 3 AS id,'error 1234' F...
How can I place these row values to columns without looping?
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I am trying to identify a list of duplicates from a table and my table looks like this: Column1-Column2 1. 1-1 2. 1-2 3. 1-3 4. 2-1 5. 2-2 6. 2-3 7. 3-1 8. 3-2 9. 3-4 10. 4-1 11. 4-2 12. 4-3 13. 4-4 14. 5-1 15. 5-2 16. 5-4 * 1 has a group of {1,2,3} * 2 has a group of {1,2,3} * And are duplicates * 3...
``` --This code produced the results I was looking for in the original post. WITH t AS ( SELECT column1, COUNT(*) c FROM #tbl GROUP BY column1 ), tt AS( SELECT t1.column1 as 'winner', t2.column1 as 'loser' FROM t t1 INNER JOIN t t2 ON ( t1.c = t2.c AND t1.column1 < t2.column1 ) WHERE NOT EXISTS...
``` WITH t AS ( SELECT column1, COUNT(*) c FROM MyTable GROUP BY column1 ) SELECT t1.column1, t2.column1 FROM t t1 INNER JOIN t t2 ON ( t1.c = t2.c AND t2.column1 > t1.column1 ) WHERE NOT EXISTS ( SELECT column2 FROM MyTable WHERE column1 = t1.column1 EXCEPT SELECT column2 FROM MyTable WHERE...
SQL Table with a list of repeating values (duplicates) to find
[ "", "sql", "sql-server", "hash", "aggregate", "checksum", "" ]
I have a table which contains a set of translations and I want to query the original table with the translations inserted (if a translation exists). For example: ``` CREATE TABLE foo ( id TEXT, key TEXT ); CREATE TABLE translations ( key TEXT, value TEXT ); INSERT INTO foo(id, key) VALUES('1', '1'); INSERT...
Like this? ``` SELECT f.id, f.key, COALESCE(t.value, f.key) AS TranslatedKey FROM foo f LEFT JOIN translations t ON f.key = t.key ``` with a left join the values from `t` will be null if no match is found. `COALESCE` returns the first non-null value from the list of inputs.
Another way, using case: ``` SELECT f.id, CASE WHEN t.key IS NULL THEN f.key ELSE t.value END AS Column2 FROM foo f LEFT JOIN translations t ON f.key=t.key ``` The coalesce way is neater in my opinion though.
How can you replace a value via a LEFT JOIN in SQL?
[ "", "sql", "sqlite", "" ]
I have a large table of businesses. There is a field with the sales of each company and I want to remove every record with sales that are over 2000000, but records are VARCHAR and have commas in them like this 2,000,000 Will something like this work? ``` DELETE FROM `tablename` WHERE `sales` > 2,000,000 ```
Remove the comma and force a number conversion ``` DELETE FROM `tablename` WHERE replace(sales, ',', '') * 1 > 2000000 ``` ### BTW it would be better to change the data type of the `sales` column to a numberic one.
``` delete from table1 where replace( replace(sales, ',', ''), '"', '' ) >=200000 ``` Here is [fiddle](http://www.sqlfiddle.com/#!2/b2b65c/1)
Removing MySQL Records From Table by Sales Amount
[ "", "mysql", "sql", "" ]
I'm sure I must be doing something stupid, but as is often the case I can't figure out what it is. I'm trying to run this query: ``` SELECT `f`.`FrenchWord`, `f`.`Pronunciation`, `e`.`EnglishWord` FROM (`FrenchWords` f) INNER JOIN `FrenchEnglishMappings` m ON `m`.`FrenchForeignKey`=`f`.`id` INNER JOIN `EnglishWords` ...
As said by the EXPLAIN, you key size is HUGE : 602, this requires MySQL to write down the data. You need to reduce (greatly) the keylen, I believe recommended is below 128. I suggest you create a column called MD5\_FrenchWord which will contain the MD5 value of FrenchWord. Then use this column for the GROUP BY. This ...
You are misusing `GROUP BY`. This clause is entirely pointless unless you also have a summary function such as `MAX(something)` or `COUNT(*)` in your `SELECT` clause. Try removing `GROUP BY` and see if it helps. It's not clear what you're trying to do with `GROUP BY`. But you might try `SELECT DISTINCT` if you're try...
MySQL query with 2 joins, large keylen leads to 'Copying to tmp table on disk' process hanging forever
[ "", "mysql", "sql", "codeigniter", "join", "sql-order-by", "" ]
i have , in sql server , a parameter as : ``` @DoBEmp = '24/6/1990' ``` passed to sql , when I try to insert it into table , this error raises : ``` Error converting data type varchar to date. ``` how can i insert it properly
Have you tried [setting the date format](http://msdn.microsoft.com/fr-fr/library/ms189491.aspx)? ``` SET DATEFORMAT dmy; ```
``` @DoBEmp = CONVERT(date,'24/6/1990',103) ``` dd/mm/yyyy is style 103 [CAST and CONVERT (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms187928.aspx)
Error converting data type varchar to date
[ "", "sql", "sql-server-2008", "" ]
Working with a legacy system, many tables have no primary keys. DB is MSSQL server 2008, db was migrated from foxpro years ago. I would like to add PK to the tables without them, but am getting push back "because it may break something." Try as I might I can think of no realistic scenario where that can occur. The pe...
Much as I hate to help you use Entity Framework, I have to say that if you have checked the column to make sure there are no nulls and no duplicates, you should be fine to declare it as a PK. Adding a new column is riskier but making an existing column a PK should be fairly straightforward and frankly if anything break...
There are no guarantees. One area where I can imagine breakage is SELECT \* statements and code that expects a certain number of columns in a certain order coming back. Adding a column, PK or not, could break that. But adding a PK for the sake of a PK doesn't really add value. A PK helps CRUD (especially the UD parts...
Can adding a new column and making it a pk to a table break existing code
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have a stored procedure that takes an input parameter `@CategoryKeys varchar`, and parses its contents into a temp table, `#CategoryKeys`. ``` -- create the needed temp table. CREATE TABLE #CategoryKeys ( CategoryKey SMALLINT ); -- fill the temp table if nece...
When you create a #TEMP table, the "scope" is bigger than just the procedure it is created in. Below is a sample: ``` IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' and ROUTINE_NAME = N'uspProc002' ) BEGIN DROP PROCEDURE [dbo]...
While understanding scoping addresses the direct need, thought it might be useful to add a few more options to the mix to elaborate on the suggestions from the comments. 1. Pass XML into the stored procedure 2. Pass a table-valued parameter into the stored procedure **1. Pass XML into the stored procedure** With XML...
How to pass a temp table as a parameter into a separate stored procedure
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have 2 tables as listed below. I need to list doctor details with the patient he has seen in the last 6 months and the number of patient he had seen. ``` - Patient PatientNo | Name | Address | DrNo (FK) | Datevisit - Doctor DrNo | Name | Contact ``` My final output should be as below ``` DrNo | Name | Contact...
Try this: ``` SELECT DrNo, Name, Contact, (SELECT COUNT(*) FROM Patient WHERE Patient.DrNo = Doctor.DrNo AND MONTHS_BETWEEN(sysdate,Patient.datevisit) <= 6) as PatientSeen FROM Doctor ```
``` select d.DrNo,d.Name,d.Contact,count(p.PatientNo) from Doctor d left join Patient p on p.DrNo =d.DrNo where MONTHS_BETWEEN(sysdate,p.Patient.datevisit) <= 6 group by d.DrNo,d.Name,d.Contact ```
Oracle SQL count with date requirement
[ "", "sql", "oracle", "" ]
``` SELECT EmailOfConsumer, COUNT(EmailOfConsumer) as 'NumberOfOrders', SUM(CAST(Total as money)) as 'TotalValue', (SUM(CAST(Total as money))/COUNT(EmailOfConsumer)) as 'AverageValue' FROM webshop GROUP BY ...
use ``` HAVING COUNT(EmailOfConsumer) = 1 ``` The having clause restricts a aggregate whereas the where clause only put restrictions on individual column data
Using group by and then having clause. Refer [this](http://www.w3schools.com/sql/sql_having.asp) ``` SELECT EmailOfConsumer, COUNT(EmailOfConsumer) as 'NumberOfOrders', SUM(CAST(Total as money)) as 'TotalValue', (SUM(CAST(Total as money))/COUNT(EmailOfConsumer)) as 'Av...
Query that Counts records with a WHERE clause
[ "", "sql", "sql-server", "count", "where-clause", "" ]
When I try to alter a data type of my table I get this horrible message from SQL Management Studion: "Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created". I already tried to do the modification by T-SQL and it worked, but why can't I just do this by desi...
I would strongly suggest that you use T-SQL to make changes, or at the very least, preview the scripts that the Designers generate before committing them. However, if you want to do this in the designer, you can turn off that lock by going to Tools...Options...Designers..Table and Database Designers.. and unclick the "...
To change the Prevent saving changes that require the table re-creation option, follow these steps: Open SQL Server Management Studio (SSMS). On the Tools menu, click Options. In the navigation pane of the Options window, click Designers. Select or clear the Prevent saving changes that require the table re-creation che...
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created
[ "", "sql", "sql-server-2008", "" ]
I am trying to retrieve some data (`coursename`) from one of my tables but the following error is coming all the time > ORA-00918: column ambiguously defined the command I am typing is: ``` select bookno,courno,coursename from booking, course,coursename where bookno = 6200 and booking.courno = course.courno and cour...
when the same column appears in several tables you need to specify which table is the one to be used. As a general rulem its always a good idea to prefix the column with the table (or alias) as improves readability and speeds up parsing. so, for your query try (changes in upper case) ``` select BOOKING.bookno,BOOKING....
You need to specify from which table the columns in `SELECT` and `WHERE` statements should be retrieved: ``` select booking.bookno, booking.courno, course.coursename from booking, course, coursename where booking.bookno = 6200 and booking.courno = course.courno and coursename.coursenameno = course.coursenameno ``` Al...
ORA-00918: column ambiguously defined
[ "", "sql", "oracle", "" ]
I have an Access Database with a table [tblManipulate] with the following four fields populated with data: ``` [tblManipulate].[Name] [tblManipulate].[Description] [tblManipulate].[Price] [tblManipulate].[Account code] ``` I also have an 150 entry table of descriptions called [tblDescLookup] that needs to be utiliz...
Something like this should do it for you. ``` Dim Description As String Dim lookupDescription As String Dim rs As DAO.Recordset Set rs = CurrentDb.OpenRecordset(SELECT * FROM tblManipulate) If Not (rs.EOF And rs.BOF) Then rs.MoveFirst 'good habit Do Until rs.EOF = True Description = rs("De...
Oy. You're going to need a loop here. I would open up tblDescLookup in a recordset: ``` Set rec = CurrentDB.OpenRecordset ("Select * from tblDescLookup") ``` Then loop through each record and run the query that way: ``` Do While rec.EOF = False Set rec2 = CurrentDB.OpenRecordset ("Select * from rec where Descri...
Using a 'lookup' table in MS-ACCESS for an update query
[ "", "sql", "ms-access", "vba", "ms-access-2010", "" ]
I want to show the value only when the sum is higher than 2 Strange output ``` select 1+3 > 2; ?column? ---------- t (1 register) ``` --- ``` ERROR: column "val" does not exist line 1: select 1+3 as val where val > 2; ^ ``` --- ``` ERROR: syntax error at or near "CASE" line ...
you cannot use derived column in `where` clause, there're many discussions on SO about this. One way to do this is to use subquery or CTE ``` select val from (select 1+3 as val) as v where val > 2 ``` or ``` with cte ( select 1+3 as val ) select val from cte where val > 2 ```
You need a subselect, because the columns defined in the select clause aren't available for use in where clauses: ``` select val from (select 1+3 as val) as vals where val > 2 ``` A CTE also works: ``` with vals as ( select 1+3 as val ) select val from vals where val > 2 ```
sum with sql and direct condition
[ "", "sql", "postgresql", "" ]
I am trying to find the oldest person in my Members' birthday table from Vermont and New York. My Members resembles the following: ``` Members ------- MemberID, Firstname, Lastname, Birthday, Region ``` I formulated the following subquery: ``` SELECT lastname FROM members WHERE region = 'VT' AND year(birthday) ...
You need to find max birthday of NY members, so that you get only one value. Then use that value to find VT member greater than that max value of NY You may try this: ``` select lastname from members where region = 'VT' and year(birthday) > (select max(birthday) from members where region = 'NY') ``` The logical ope...
``` select top 1 * from table where region='vermont' or region ='newyork' order by year(birthday) desc ```
The oldest person in a birthday table. SQL subquery
[ "", "mysql", "sql", "" ]
Previously for my PHP app, I used a cron job that increments the health of a user in SQL every 10 minutes and the cron job script incremented the health of all users. For my next app, I tried using MySQL events to increment the health every minutes for each individual user and ran into some problems with them not work...
Instead updating *every* record in the database every 10 minutes, store a last-modified timestamp in the same row as the health. Every time you read the player\_health from the database, add (current\_time - last\_modified) / (10 min) to the value. Every time you write player\_health to the database, update the last\_m...
I would create a rake task that increases all users' health by 10, and call it using the awesome [whenever gem](https://github.com/javan/whenever) every 10 minutes. **UPDATE** However, as Dan said in his comment, it might be inefficient to do such a huge DB update every 10 seconds (especially if you have huge number ...
Best way to increment health of a user in a game every minute
[ "", "sql", "ruby-on-rails", "" ]
I have a great problem with joining two MSSQL databases together (on the same server) using LEFT JOIN. I run this SQL from the database OLAB\_DB and get the error: ``` The multi-part identifier "OLAP_DB.dbo.OLAP_invoice.UserID" could not be bound. ``` There seem to be a problem with the DB not being able to find itse...
You can try this: ``` SELECT TOP 200 COALESCE(LTRIM(RTRIM(contact_db.dbo.ContactTable.EmailAdr)),LTRIM(RTRIM(contact_db.dbo.CustomerTable.EmailAdr))) AS EMAIL, OLAP_invoice.OrdreLinjeID AS ORDERNO OLAP_invoice.SalgsPris AS PRICE, OLAP_invoice.UserID AS CONTACTID FROM OLAP_invoice LEFT JOIN co...
You are selecting from `OLAP_invoice`, but joining to `OLAP_DB.dbo.OLAP_invoice`. You need to qualify the table exactly the same every time, or use an alias. So either: ``` FROM OLAP_DB.dbo.OLAP_invoice left join contact_db.dbo.ContactTable on OLAP_DB.dbo.OLAP_invoice... ``` OR ``` FROM ROM OLAP_invoice LEFT JOIN on...
Error when left joining two databases (SQL Server)
[ "", "sql", "sql-server", "database", "join", "left-join", "" ]
I wrote a query which splits a string and show me as a value I want using SUBSTR ``` SELECT SUBSTR ('imagelocation/r1.jpg', 15) AS image_location FROM dual ``` I am getting the output as r1.jpg but I only want the value to come as r1. Please help
Try this: ``` SELECT SUBSTR('imagelocation/r1.jpg',15,2) AS image_location FROM dual ```
``` select SUBSTR ( 'imagelocation/r1.jpg', INSTR('imagelocation/r1.jpg', '/')+1, LENGTH('imagelocation/r1.jpg') - INSTR('imagelocation/r1.jpg', '.') - 1 ) AS image_location FROM dual ``` **[SUBSTR Function in Oracle](http://docs.oracle.com/javadb/10.6.1.0/ref/rrefsqlj93082.html)**...
Splitting of a String using query
[ "", "sql", "oracle", "oracle10g", "" ]
I have used this SP before. Now, I am trying to permission a user to 50 odd databases that start with the same letters, using the code below. It looks like it does not like "GO" in the code. Why is that ? and what is the work around? Thanks for your time.. :) RM ``` exec sp_MSForEachDB ' IF ''?'' LIKE ''MYDBNames%''...
I just explained this in another question yesterday ([here](https://stackoverflow.com/questions/20102165/sql-server-use-database-precedence-issue/20102814#20102814)). This essence is this: `GO` isn't a SQL statement, it's an SSMS/SQLCMD command that is used to separate batches (groups of SQL statements that are compile...
The word `GO` is a batch separator and is not a SQL keyword. In SSMS you can go to options and change it to anything - `COME` for example. Try this: ``` exec sp_MSForEachDB ' IF ''?'' LIKE ''MYDBNames%'' BEGIN; Use [?]; CREATE USER [MYDOMAIN\Analysts] FOR LOGIN [MYDOMAIN\Analysts]; EXEC sp_addrolemember N''db_owner''...
sp_MSForEachDB doesn't seem to like GO
[ "", "sql", "sql-server", "t-sql", "" ]
My table has entries like ``` 01-JAN-92 12.00.00.000000000 AM -04:00 01-JAN-86 12.00.00.000000000 AM -04:00 03-JAN-01 12.00.00.000000000 AM +00:00 03-JAN-01 12.00.00.000000000 AM -04:00 ``` And I want to be able to count all the entries that I have for a specific day, instead of taking into consideration the time as ...
You can use the `TRUNC` to get rid of the time portion: ``` SELECT TRUNC(ACTIONDATE, 'DD'), count(1) AS count FROM mytable GROUP BY TRUNC(ACTIONDATE, 'DD'); ``` `TRUNC` truncates the part of the date up to the specified part of it, in this case, the day. For example, using TRUNC with 'DD' on `SYSDATE` returns: ``...
Use date() function: ``` SELECT DATE(ACTIONDATE), COUNT(ACTIONDATE) AS count FROM mytable GROUP BY DATE(ACTIONDATE) ``` EDIT: Sorry. This is in fact mysql format. For the Oracle format, the chosen answer is the more appropriate.
SQL group by portion of the string
[ "", "sql", "oracle", "" ]
Here is a basic example of what I am trying to achieve: ``` create table #testing ( tab varchar(max), a int, b int, c int ) insert into #testing VALUES ('x',1, 2, 3) insert into #testing VALUES ('y',1, 2, 3) insert into #testing VALUES ('x', 4, 5, 6) select * from #testing ``` Which will Produce the table:...
Use `not exists`: ``` select a.* from #testing a where a.tab = 'x' and not exists ( select * from #testing t where t.a = a.a and t.b = a.b and t.c = a.c and t.tab = 'y' ) ``` **And here you get SQL Fiddle demo: [DEMO](h...
Although the answer from @gzaxx does produce a correct result for this test data, the more generalized version is below, where I left 'x' and 'y' out of the statements. ``` select a.* from #testing a where not exists ( select * from #testing t where t.a = a.a ...
SQL: EXCEPT Query
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
I have a table `Person` with a column `id` that references a column `id` in table `Worker`. What is the difference between these two queries? They yield the same results. ``` SELECT * FROM Person JOIN Worker ON Person.id = Worker.id; ``` and ``` SELECT * FROM Person, Worker WHERE Person.id = Worker.id; `...
**There is no difference at all**. First representation makes query more readable and makes it look very clear as to which join corresponds to which condition.
The queries are logically equivalent. The comma operator is equivalent to an `[INNER] JOIN` operator. The comma is the older style join operator. The JOIN keyword was added later, and is favored because it also allows for OUTER join operations. It also allows for the join predicates (conditions) to be separated from ...
What's the difference between comma separated joins and join on syntax in MySQL?
[ "", "mysql", "sql", "join", "syntax", "" ]
I have a table in Sql Sever 2005 : ``` id eid name datetime -- |----|------- |------------------------ 1 | 1 | john | 2013-11-18 15:30:00.000 2 | 1 | john | 2013-11-18 14:10:00.000 3 | 1 | john | 2013-11-18 13:30:00.000 4 | 1 | john | 2013-11-18 16:00:00.000 5 | 1 | john | 2013-11-18 17:0...
Give this a try: ``` WITH BEFORE AS ( SELECT eid, max(datetime) date FROM t WHERE datetime <= '2013-11-18 15:50:00.000' GROUP BY eid ), AFTER AS ( SELECT eid, min(datetime) date FROM t WHERE datetime >= '2013-11-18 15:50:00.000' GROUP BY eid ) SELECT t.eid, t.name, max(b.date) beforeDate, min(a.date) after...
Try This... ``` SELECT MIN(id) [id], eid, name, (SELECT MAX(datetime) FROM table t1 WHERE t1.datetime < inputdate AND t1.eid = t.eid) [AdjacentMinimumDateTime], (SELECT MIN(datetime) FROM table t2 WHERE t2.datetime > inputdate AND t2.eid = t.eid) [AdjacentMaximumDateTime] FROM tab...
SQL Server - Need Minimum and Maximum date time adjacent(closest) to input date
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I keep getting this error `Missing semicolon (;) at end of SQL statement.` when I run this code: ``` Dim cmd3 As OleDbCommand = New OleDbCommand("INSERT INTO Tickers (Quarter_Balance_Sheets) VALUES (Scrapalbe) WHERE Ticker = A;", con) cmd3.ExecuteNonQuery() ``` What am I doing wrong?
Edited.. Sorry. After reading again you cannot use WHERE on an INSERT statement, loose the WHERE clause or make an UPDATE statement. INSERT INTO ... WHERE is not a valid query. If the insert you've posted has correct values and columns, the update should be: ``` Dim cmd3 As OleDbCommand = New OleDbCommand("UPDATE T...
Missing quotes `WHERE Ticker = 'A'` and in `VALUES ('Scrapalbe')` edit: @Engerlost is right, `where` is not applicable to `insert`; you still need quotes but drop `where...` completely
Missing semicolon (;) at end of SQL statement. Semicolon already exists
[ "", "sql", "vb.net", "where-clause", "insert-into", "oledbcommand", "" ]
My question is very simple but I cannot get my head around my statement: ``` SELECT * FROM table 1 WHERE (row1 = 0 AND row2 > 0) OR (row3 is NULL AND row4 > 0) ``` This gives me a selection of rows that is correct for one option. What I want is making a selection of all rows where the where clause is not true...
I think this is what you are looking for? I've assumed you meant fields rather than rows though... ``` SELECT * FROM table1 WHERE not exists (select * from table1 where ((field1 = 0 and field2 > 0) OR (field3 IS NULL AND field4 > 0))) ``` Maybe see this for further information on NOT IN AND NOT EXISTS to exclude r...
I suspect your problem is to do with `NULL` values in columns, because any predicate with NULL evaluates to NULL, so is neither true or false: Imagine a simple table `T` with one column (Col): ``` Col ----- 1 2 3 NULL ``` So if we run: ``` SELECT Col FROM T WHERE Col = 1; ``` We get one row, where Col = 1, t...
sql multiple conditions together not true
[ "", "sql", "" ]
How can I add characters and chain two db queries in the puts statement of Ruby? I'm using sqlite 3 The desired output I want is `Sam - 32` I imagine the code would look something like this: `puts $db.execute(SELECT first_name FROM info) + " - " + $db.execute(SELECT age FROM info)` I know that there is an issue wi...
At least with sqlite3, this is what gives the desired output: ``` puts $db.execute(SELECT first_name || ' - ' || age FROM info) ```
Is this what you are looking for? ``` $db.execute("SELECT CONCAT(first_name, ' - ', age) as name_and_age FROM info") ```
Formatting SQL output in Ruby
[ "", "sql", "ruby", "" ]
I have a table that have 5 columns, and instead of update, I've done insert of all rows(stupid mistake). How to get rid of duplicated records. They are identical except of the id. I can't remove all records, but I want do delete half of them. ex. table: ``` +-----+-------+--------+-------+ | id | name | name2 | us...
Please try: ``` with c as ( select *, row_number() over(partition by name, name2, [user] order by id) as n from YourTable ) delete from c where n > 1; ```
Try the following. ``` DELETE FROM MyTable WHERE ID NOT IN ( SELECT MAX(ID) FROM MyTable GROUP BY Name, Name2, User) ``` That is untested so may need adapting. The following video will provide you with some more information about this query. [Video](http://www.youtube.com/watch?v=ioDJ0xVOHDY)
SQL delete almost identical rows
[ "", "sql", "sql-server", "duplicates", "sql-delete", "" ]
I have 3 tables containing similar rows of data. I need to select 100 rows from all of the three tables with the following conditions: No more than 25 rows can be selected from Table A --> (name it count\_a) No more than 40 rows can be selected from Table B --> (count\_b) Any number of rows can be selected from Tabl...
Try to add `WHERE ROWNUM <= 100` to the last select: ``` SELECT * FROM ( SELECT TABLE_A.*, 1 as OrdRow FROM TABLE_A WHERE ROWNUM <= 25 UNION ALL SELECT TABLE_B.*, 2 as OrdRow FROM TABLE_B WHERE ROWNUM <= 40 UNION ALL SELECT TABLE_C.*, 3 as OrdRow FROM TABLE_C WHERE ROWNUM <= 100 ) WHERE ROWNUM <=...
Technically, you'd have to do something like this in order to guarantee that you'll always get rows from TABLE\_A and TABLE\_B if they exist: ``` SELECT * FROM ( SELECT * FROM ( SELECT 'A' t, TABLE_A.* FROM TABLE_A WHERE ROWNUM <= 25 UNION ALL SELECT 'B' t, TABLE_B.* FROM TABLE_B WHERE ROWNUM <= 40 ...
How can I collectively select 100 rows from 3 different tables?
[ "", "sql", "oracle", "" ]
I'm trying to write an aggregate query in SQL which returns the count of all records joined to a given record in a table; If no records were joined to the given record, then the result for that record should be `0`: ## Data My database looks like this (I'm not able to change the structure, unfortunately): ``` MESSAG...
How about something like this: ``` SELECT m.MESSAGEID, sum((case when mp.messageid is not null then 1 else 0 end)) FROM MESSAGE m LEFT JOIN MESSAGEPART mp ON mp.MESSAGEID = m.MESSAGEID GROUP BY m.MESSAGEID; ``` The COUNT() function will count every row, even if it has null. Using SUM() and CASE, you can count only no...
You *first* want to count in your messaepart table before joining, i think. Try this: ``` SELECT m.MessageId , COALESCE(c, 0) as myCount FROM MESSAGE m LEFT JOIN (SELECT MESSAGEID , count(*) c FROM MESSAGEPART GROUP BY MESSAGEID) mp ON mp.MESSAGEID = m....
Counting number of joined rows in left join
[ "", "sql", "oracle", "join", "count", "left-join", "" ]
I have this table in my Database and i hava a history with entrys: Tabelname: Activity ``` ActivityID | DateBegin | DateEnd 1 2013-01-01 2013-01-15 1 2013-01-15 9999-12-31 2 2013-01-20 2013-03-15 ``` Now i want to write a Query which will return the id with the DateEnd = 9999...
``` SELECT ActivityID FROM dbo.Activity As x WHERE NOT EXISTS ( SELECT ActivityID FROM dbo.Activity WHERE DateEnd ='9999-12-31' AND ActivityID = x.ActivityID ) ```
If you want to return all the IDs that don't have any row with date 9999-12-31, you should first check which IDs you don't want to be returned, then avoid them in your query. So the query becomes: ``` SELECT ActivityID FROM [dbo].[Activity] WHERE ActivityID NOT IN (SELECT ActivityID from [dbo]....
sql - Select Statement where not exists a condition for each id ?
[ "", "sql", "sql-server", "" ]
I am using Lucene to perform queries on a subset of SQL data which returns me a scored list of RecordIDs, e.g. 11,4,5,25,30 . I want to use this list to retrieve a set of results from the full SQL Table by RecordIDs. So `SELECT * FROM MyFullRecord where RecordID in (11,5,3,25,30)` I would like the retrieved list to ...
You can record your list into a table or table variable with sorting priorities. And then join your table with this sorting one. ``` DECLARE TABLE @tSortOrder (RecordID INT, SortOrder INT) INSERT INTO @tSortOrder (RecordID, SortOrder) SELECT 11, 1 UNION ALL SELECT 5, 2 UNION ALL SELECT 3, 3 UNION ALL SELECT 25, 4 UNIO...
Instead of creating a searched order by statement, you could create an in memory table to join. It's easier on the eyes and definitely scales better. **SQL Statement** ``` SELECT mfr.* FROM MyFullRecord mfr INNER JOIN ( SELECT * FROM (VALUES (1, 11), (2, 5), ...
MSSQL ORDER BY Passed List
[ "", "sql", "sql-server", "" ]
I need to optimize SELECT query in order to improve the performance. I am using ORACLE 10g. Below is my table: ``` CREATE TABLE TRNSCTN ( TRNSCTN_ID VARCHAR2(32) NOT NULL, TRNSCTN_DOC VARCHAR2(60) NOT NULL, TRNSCTN_TYPE VARCHAR2(60) NOT NULL, STATUS NUMBER...
You can use left-join as i wrote below and you can consider giving parallel hint (e.g /\*+ parallel \*/ ) ``` SELECT sub.TRNSCTN_ID, sub.TRNSCTN_DOC, sub.TRNSCTN_TYPE, sub.STATUS, sub.TRNSCTN_CREATEDDATE, sub.TRNSCTN_CREATEDBY, sub.TRNSCTN_CHANGEDDATE, sub.TRNSCTN_CHANGEDBY, sub.PAR...
``` SELECT TRNSCTN_ID, TRNSCTN_DOC, TRNSCTN_TYPE, STATUS, TRNSCTN_CREATEDDATE, TRNSCTN_CREATEDBY, TRNSCTN_CHANGEDDATE, TRNSCTN_CHANGEDBY, PARENT_LINK, CASE WHEN NOT EXISTS (SELECT 1 FROM TRNSCTN sub ...
Oracle SQL SELECT subquery Optimization
[ "", "sql", "oracle", "select", "subquery", "query-optimization", "" ]
Verified sql syntax code with <http://sqlformat.appspot.com/> and its still not working.... ``` $sql = "CREATE TABLE test (prime_key AUTO-INCREMENT PRIMARY KEY, train_num INT, train_type CHAR(50))"; ``` Its giving me "near 'AUTO-INCREMENT PRIMARY...'" in the error message. What am I missing?
You need to use an underscore `_`, not a dash (`-`). You're also missing a data type for your `prime_key` column: ``` CREATE TABLE test ( prime_key INT AUTO_INCREMENT PRIMARY KEY, train_num INT, train_type CHAR(50) ) ```
It is [**`AUTO_INCREMENT`**](http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html) not `AUTO-INCREMENT`
Create Table SQL Syntax Error - What am I doing wrong?
[ "", "mysql", "sql", "" ]
In this [sqlfiddle](http://sqlfiddle.com/#!3/b0665/36/0) I am trying to replace CompanyName to something else if it is null but apparently I cannot. I tried case statement and other techniques but it did not work. Is there away to replace CompanyName lets say by 'Not Given' if the company is null. I must use OUTER APP...
Please try: ``` select p.*, isnull(czip.companyname, 'Not Given') companyname from Person p outer apply ( select companyname from Company c where p.companyid = c.companyId ) Czip ```
``` SELECT Coalesce(companyname, 'Not Given') As companyname ... ```
How to replace NULL in SQL OUTER APPLY
[ "", "sql", "sql-server", "join", "replace", "null", "" ]
Hi I have a query as fallows ``` INSERT INTO CPQ (BackLog_ID, Priority, Category, Type, Country, Region, TN, [Date Entered], Source, Brand, [Remote #], [Target #], ...
1) You have a PK column, which is not auto-increment 2) You try to insert something to that table without assigning a value to your PK 3) you get an error that says you cannot do that I am not really sure what more you need for a solution, but since 3) is the result of 1) and 2), you will have to change 1) or 2). S...
The problem is you are trying to insert null value into CPQ\_ID column, The best way is to set CPQ\_ID column to auto increment , Sample table create code with Auto Increment enabled ``` CREATE TABLE [dbo].[tablename]( [CPQ_ID] [int] IDENTITY(1,1) NOT NULL ) ON [PRIMARY] ``` This code " `IDENTITY(1,1) NOT NULL`"...
Insert query with Auto number
[ "", "sql", "sql-server", "" ]
I have the following code in a code-first migration: ``` public partial class RunSQLInit : DbMigration { public override void Up() { this.Sql(SqlFiles.Create_Job_ClearExpiredData); } [...] } ``` where `SqlFiles.Create_Job_ClearExpiredData` is a resx-file returning an SQL-file as a string. The...
The answer to my problem was to simply use this inside the SQL-file: ``` set @databaseName = db_name() ``` Since the current context is already the database I will use for the job, it's already there. Too easy.
I had to declare my @DBName variable in order to set it. Error otherwise: > Must declare the scalar variable "@DBName". Complete code: ``` Sql("DECLARE @DBName nvarchar(50), @SQLString nvarchar(200)\r\n" + "SET @DBName = db_name();\r\n" + "SET @SQLString = \'ALTER DATABASE [\' + @DBName + \'] COLLATE Latin1_...
Access the database name inside Up in DbMigration
[ "", ".net", "sql", "sql-server", "entity-framework", "ef-code-first", "" ]
I get confused on a sql statement and I kind of need your help. Below are my table entitled (tblfood) contents: ``` ID Food_Name Main_Ingredient Drink 1 Ham n Coke Ham Coke 2 Cheese n Tea Cheese Ice Tea 3 Ham n Coke Ham Coke 4 Ham n Coke...
How about this, selecting the max id considering you want a single id not multiple if you want multiple you need to rely on Order By clause solution. ``` SELECT MAX(id) FROM tblfood WHERE Food_Name='Chicken Sandwich'; ```
``` SELECT ID FROM tblfood WHERE Food_Name = 'Chicken Sandwich' ORDER BY ID DESC LIMIT 1 ```
Fetch last ID where column is equal to a string
[ "", "mysql", "sql", "" ]
I have installed an Oracle 12c database on my system. I had an application which need to access the database. Previously in Oracle 11g, I used the following commands to create an user. ``` create user name identified by name; grant connect,create session,resource,create view to name; ``` Can anyone tell me how to ...
Best Practice is to create a tablespace and assign that to the User. Just to make it easier to understand use same name for username and tablespace `CREATE BIGFILE TABLESPACE C##1 DATAFILE '/path/to/datafile/C##1.dbf' SIZE 10M AUTOEXTEND ON NEXT 5M MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEM...
You should also give the user a quota on his default tablespace: ``` CREATE USER name IDENTIFIED BY name DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp QUOTA 50M /* or any other number that makes sense */ ON users GRANT CONNECT, CREATE SESSION, RESOURCE, CREATE VIEW TO name; ```
Regarding Users in Oracle 12c
[ "", "sql", "oracle", "oracle12c", "" ]
For a school assignment, I have to create a database and run reports. I've created code and a classmate has also created code and it runs the same thing, but his is in a format I've not seen and don't quite understand. Here is mine: ``` SELECT Course.Name AS 'Course Name', Program.Name AS 'Program Name' FROM...
There's a few differences. First off, he's creating a `VIEW` rather than *just* a select statement: ``` CREATE VIEW NumberOfCoursePerProgram AS ``` Once the view is created, you can query the view just as you would a table: ``` SELECT * FROM NumberOfCoursePerProgram; ``` Second, he's using an ANSI JOIN rather than ...
These are called [alias](http://technet.microsoft.com/en-us/library/ms187455%28v=SQL.105%29.aspx) in SQL. Alias is basically created to give more readability and for better ease of writing code. > The readability of a SELECT statement can be improved by giving a > table an alias, also known as a correlation name or ra...
Difference between SQL Server codes?
[ "", "sql", "sql-server", "" ]